How to resolve the algorithm Knuth's algorithm S step by step in the Sidef programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Knuth's algorithm S step by step in the Sidef programming language

Table of Contents

Problem Statement

This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).

Note: A class taking n and generating a callable instance/function might also be used.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Knuth's algorithm S step by step in the Sidef programming language

Source code in the sidef programming language

func s_of_n_creator(n) {
    var i = 0
    var sample = []
    { |item|
        if (++i <= n) {
            sample << item;
        }
        elsif (i.rand < n) {
            sample[n.rand] = item;
        }
        sample;
    }
}

var items = 0..9;
var bin = [];

100000.times {
    var s_of_n = s_of_n_creator(3);
    var sample = []
    for item in items {
        sample = s_of_n(item);
    }
    for s in sample {
        bin[s] := 0 ++;
    }
}

say bin;


  

You may also check:How to resolve the algorithm Perfect numbers step by step in the Slate programming language
You may also check:How to resolve the algorithm Arrays step by step in the R programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Action! programming language
You may also check:How to resolve the algorithm Non-decimal radices/Input step by step in the Julia programming language
You may also check:How to resolve the algorithm Pascal's triangle step by step in the JavaScript programming language