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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Knuth's algorithm S step by step in the Common Lisp 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 Common Lisp programming language

Source code in the common programming language

(defun s-n-creator (n)
  (let ((sample (make-array n :initial-element nil))
        (i 0))
    (lambda (item)
      (if (<= (incf i) n)
          (setf (aref sample (1- i)) item)
        (when (< (random i) n)
          (setf (aref sample (random n)) item)))
      sample)))

(defun algorithm-s ()
  (let ((*random-state* (make-random-state t))
        (frequency (make-array '(10) :initial-element 0)))
    (loop repeat 100000
          for s-of-n = (s-n-creator 3)
          do (flet ((s-of-n (item)
                      (funcall s-of-n item)))
               (map nil
                    (lambda (i)
                      (incf (aref frequency i)))
                    (loop for i from 0 below 9
                          do (s-of-n i)
                          finally (return (s-of-n 9))))))
    frequency))

(princ (algorithm-s))


#(30026 30023 29754 30017 30267 29997 29932 29990 29965 30029)


  

You may also check:How to resolve the algorithm Draw a sphere step by step in the Wren programming language
You may also check:How to resolve the algorithm Greatest element of a list step by step in the Raku programming language
You may also check:How to resolve the algorithm Object serialization step by step in the Neko programming language
You may also check:How to resolve the algorithm Balanced ternary step by step in the Factor programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the MATLAB programming language