How to resolve the algorithm One of n lines in a file step by step in the OCaml 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 OCaml 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 OCaml programming language
Source code in the ocaml programming language
let one_of_n n =
let rec aux i r =
if i >= n then r else
if Random.int (i + 1) = 0
then aux (succ i) i
else aux (succ i) r
in
aux 1 0
let test ~n ~trials =
let ar = Array.make n 0 in
for i = 1 to trials do
let d = one_of_n n in
ar.(d) <- succ ar.(d)
done;
Array.iter (Printf.printf " %d") ar;
print_newline ()
let () =
Random.self_init ();
test ~n:10 ~trials:1_000_000
You may also check:How to resolve the algorithm Fork step by step in the HicEst programming language
You may also check:How to resolve the algorithm Averages/Median step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the min programming language
You may also check:How to resolve the algorithm Euler's constant 0.5772... step by step in the Python programming language
You may also check:How to resolve the algorithm Prime decomposition step by step in the D programming language