How to resolve the algorithm One of n lines in a file step by step in the F# 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 F# 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 F# programming language
Source code in the fsharp programming language
open System
[<EntryPoint>]
let main args =
let rnd = new Random()
let one_of_n n =
let rec loop i r =
if i >= n then r else
if rnd.Next(i + 1) = 0
then loop (i + 1) i
else loop (i + 1) r
loop 1 0
let test n trials =
let ar = Array.zeroCreate n
for i = 1 to trials do
let d = one_of_n n
ar.[d] <- 1 + ar.[d]
Console.WriteLine (String.Join(" ", ar))
test 10 1000000
0
You may also check:How to resolve the algorithm AKS test for primes step by step in the Clojure programming language
You may also check:How to resolve the algorithm Substring step by step in the Fortran programming language
You may also check:How to resolve the algorithm Copy a string step by step in the Erlang programming language
You may also check:How to resolve the algorithm Reverse words in a string step by step in the D programming language
You may also check:How to resolve the algorithm Matrix multiplication step by step in the ERRE programming language