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

Source code in the ada programming language

with Ada.Text_IO, Ada.Numerics.Float_Random;

procedure One_Of_N is

   Num_Of_Lines: constant Positive := 10;

   package Rnd renames Ada.Numerics.Float_Random;
   Gen: Rnd.Generator; -- used globally

   function Choose_One_Of_N(Last_Line_Number: Positive) return Natural is
      Current_Choice: Natural := 0;
   begin
      for Line_Number in 1 .. Last_Line_Number loop
        if (Rnd.Random(Gen) * Float(Line_Number) <= 1.0) then
           Current_Choice := Line_Number;
        end if;
      end loop;
      return Current_Choice;
   end Choose_One_Of_N;

   Results: array(1 .. Num_Of_Lines) of Natural := (others => 0);
   Index: Integer range 1 .. Num_Of_Lines;

begin
   Rnd.Reset(Gen);
   for I in 1 .. 1_000_000 loop    -- compute results
      Index := Choose_One_Of_N(Num_Of_Lines);
      Results(Index) := Results(Index) + 1;
   end loop;

   for R in Results'Range loop    -- output results
      Ada.Text_IO.Put(Integer'Image(Results(R)));
   end loop;
end One_Of_N;


  

You may also check:How to resolve the algorithm Knapsack problem/Unbounded step by step in the Scala programming language
You may also check:How to resolve the algorithm Perfect numbers step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Dutch national flag problem step by step in the Picat programming language
You may also check:How to resolve the algorithm Keyboard input/Keypress check step by step in the D programming language
You may also check:How to resolve the algorithm Greatest element of a list step by step in the Clojure programming language