How to resolve the algorithm One of n lines in a file step by step in the D 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 D 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 D programming language
Source code in the d programming language
import std.stdio, std.random, std.algorithm;
// Zero-based line numbers.
int oneOfN(in int n) {
int choice = 0;
foreach (immutable i; 1 .. n)
if (!uniform(0, i + 1))
choice = i;
return choice;
}
void main() {
int[10] bins;
foreach (immutable i; 0 .. 1_000_000)
bins[10.oneOfN]++;
bins.writeln;
writeln("Total of bins: ", bins[].sum);
}
You may also check:How to resolve the algorithm Dragon curve step by step in the jq programming language
You may also check:How to resolve the algorithm Primality by trial division step by step in the Erlang programming language
You may also check:How to resolve the algorithm Ternary logic step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Emirp primes step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Wieferich primes step by step in the Phix programming language