How to resolve the algorithm One of n lines in a file step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

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

Source code in the jq programming language

export LC_ALL=C
< /dev/random tr -cd '0-9' | fold -w 4 | jq -Mnr -f program.jq


# oneOfN presupposes an unbounded stream 
# of 4-digit PRNs uniformly distributed on [0-9999]
def oneOfN:
  reduce range(2; 1+.) as $i (1;
    if (input / 10000) < (1/$i) then $i else . end);
 
def n: 10;
def repetitions: 1e6;

( reduce range(0; repetitions) as $i (null;
    (n|oneOfN) as $num
    | .[$num-1] += 1 )) as $freqs
|  range(1; 1+n) | "Line\(.) \($freqs[.-1] )"

  

You may also check:How to resolve the algorithm Mandelbrot set step by step in the Wren programming language
You may also check:How to resolve the algorithm Primality by trial division step by step in the Befunge programming language
You may also check:How to resolve the algorithm Miller–Rabin primality test step by step in the D programming language
You may also check:How to resolve the algorithm Display an outline as a nested table step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Queue/Usage step by step in the UNIX Shell programming language