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

Source code in the purebasic programming language

Procedure.f randomFloat()
   ProcedureReturn Random(1000000) / 1000000
EndProcedure

Procedure one_of_n(n)
  Protected linesRead, lineChosen
  While linesRead < n 
    linesRead + 1
    If randomFloat() <= (1.0 / (linesRead))
       lineChosen = linesRead
    EndIf
  Wend
  ProcedureReturn lineChosen
EndProcedure

If OpenConsole()
  #testFileLineCount = 10
  #simulationCount = 1000000
  Define i
  Dim a(#testFileLineCount) ;index 0 is not used
  For i = 1 To #simulationCount
    x = one_of_n(#testFileLineCount)
    a(x) + 1
  Next
  
  For i = 1 To #testFileLineCount
    Print(Str(a(i)) + "  ")
  Next
  PrintN("")
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf

  

You may also check:How to resolve the algorithm Command-line arguments step by step in the Lingo programming language
You may also check:How to resolve the algorithm Primes - allocate descendants to their ancestors step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Rename a file step by step in the Julia programming language
You may also check:How to resolve the algorithm Execute SNUSP step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Stem-and-leaf plot step by step in the Julia programming language