Knuth's algorithm S: Difference between revisions

(→‎Tcl: Added implementation)
Line 23:
* [[One of n lines in a file]]
* [[Accumulator factory]]
 
=={{header|Common Lisp}}==
<lang lisp>(setf *random-state* (make-random-state t))
 
(defun make-selector (n)
(let ((i 0) res)
#'(lambda (&optional (x nil x-p))
(if (and x-p (< (random (incf i)) n))
(if (< (length res) n)
(push x res)
(setf (elt res (random n)) x)))
res)))
 
;;; test
(loop repeat 100000
with freq = (make-array 10 :initial-element 0)
do (let ((f (make-selector 3)))
(mapc f '(0 1 2 3 4 5 6 7 8 9))
(mapc (lambda (i) (incf (aref freq i)))
(funcall f)))
finally (prin1 freq))</lang>output<lang>#(30026 30023 29754 30017 30267 29997 29932 29990 29965 30029)</lang>
 
=={{header|Python}}==
Anonymous user