How to resolve the algorithm One of n lines in a file step by step in the Clojure programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm One of n lines in a file step by step in the Clojure programming language
Table of Contents
Problem Statement
A method of choosing a line randomly from a file: Is to:
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
Let's start with the solution:
Step by Step solution about How to resolve the algorithm One of n lines in a file step by step in the Clojure programming language
Source code in the clojure programming language
(defn rand-seq-elem [sequence]
(let [f (fn [[k old] new]
[(inc k) (if (zero? (rand-int k)) new old)])]
(->> sequence (reduce f [1 nil]) second)))
(defn one-of-n [n]
(rand-seq-elem (range 1 (inc n))))
(let [countmap (frequencies (repeatedly 1000000 #(one-of-n 10)))]
(doseq [[n cnt] (sort countmap)]
(println n cnt)))
1 99350
2 99933
3 99820
4 100266
5 100675
6 100370
7 99842
8 100020
9 100342
10 99382
(require '[clojure.java.io :as io])
(defn rand-line [filename]
(with-open [reader (io/reader filename)]
(rand-seq-elem (line-seq reader)))
You may also check:How to resolve the algorithm Digital root step by step in the jq programming language
You may also check:How to resolve the algorithm Catalan numbers step by step in the MAD programming language
You may also check:How to resolve the algorithm Josephus problem step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Operator precedence step by step in the Plain English programming language
You may also check:How to resolve the algorithm Strong and weak primes step by step in the Wren programming language