How to resolve the algorithm One of n lines in a file step by step in the Euphoria 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 Euphoria 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 Euphoria programming language
Source code in the euphoria programming language
-- One of n lines in a file
include std/rand.e
include std/math.e
function one_of_n(integer n)
integer line_num = 1
for i = 2 to n do
if rnd() < 1 / i then
line_num = i
end if
end for
return line_num
end function
procedure main()
integer num_reps = 1000000, num_lines_in_file = 10
sequence lines = repeat(0,num_lines_in_file)
for i = 1 to num_reps do
lines[one_of_n(num_lines_in_file)] += 1
end for
for i = 1 to num_lines_in_file do
printf(1,"Number of times line %d was selected: %g\n", {i,lines[i]})
end for
printf(1,"Total number selected: %d\n", sum(lines) )
end procedure
main()
You may also check:How to resolve the algorithm Temperature conversion step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Factorial base numbers indexing permutations of a collection step by step in the Raku programming language
You may also check:How to resolve the algorithm Date manipulation step by step in the RPL programming language
You may also check:How to resolve the algorithm Left factorials step by step in the Tcl programming language
You may also check:How to resolve the algorithm Averages/Median step by step in the PARI/GP programming language