Skip to content

Instantly share code, notes, and snippets.

@cls
Last active May 25, 2018 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cls/48c497827f20f01a9a975dcfaa55e631 to your computer and use it in GitHub Desktop.
Save cls/48c497827f20f01a9a975dcfaa55e631 to your computer and use it in GitHub Desktop.
Reservoir sampling over a list in Common Lisp
(defun sample-list (items &optional (size 1))
(let ((sample (make-array size :fill-pointer 0)))
(loop for item in items
for enum from 1
if (<= enum size)
do (vector-push item sample)
else
do (let ((rand (random enum)))
(when (< rand size)
(setf (aref sample rand) item)))
finally (return sample))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment