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

Source code in the seed7 programming language

$ include "seed7_05.s7i";

const func integer: one_of_n (in integer: n) is func
  result
    var integer: r is 1;
  local
    var integer: i is 0;
  begin
    for i range 2 to n do
      if rand(1, i) = 1 then
        r := i;
      end if;
    end for;
  end func;

const proc: main is func
  local
    var array integer: r is 10 times 0;
    var integer: i is 0;
  begin
    for i range 1 to 1000000 do
      incr(r[one_of_n(10)]);
    end for;
    for i range 1 to 10 do
      write(r[i] <& " ");
    end for;
    writeln;
  end func;

  

You may also check:How to resolve the algorithm JSON step by step in the 8th programming language
You may also check:How to resolve the algorithm Esthetic numbers step by step in the Factor programming language
You may also check:How to resolve the algorithm Reverse words in a string step by step in the LiveScript programming language
You may also check:How to resolve the algorithm File size step by step in the HicEst programming language
You may also check:How to resolve the algorithm MD5 step by step in the Frink programming language