How to resolve the algorithm One of n lines in a file step by step in the Icon and Unicon 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 Icon and Unicon 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 Icon and Unicon programming language

Source code in the icon programming language

procedure main() # one of n
   one_of_n_test(10,1000000)
end
 
procedure one_of_n(n)
   every i := 1 to n do 
      choice := (?0  < 1. / i, i)
   return \choice | fail
end
 
procedure one_of_n_test(n,trials)
   bins := table(0)
   every i := 1 to trials do
         bins[one_of_n(n)] +:= 1
   every writes(bins[i := 1 to n]," ")
   return bins
end


  

You may also check:How to resolve the algorithm Send an unknown method call step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Execute Brain step by step in the Elena programming language
You may also check:How to resolve the algorithm Colour pinstripe/Display step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Prime numbers whose neighboring pairs are tetraprimes step by step in the C++ programming language
You may also check:How to resolve the algorithm Almost prime step by step in the Potion programming language