Skip to content

Instantly share code, notes, and snippets.

@jtzeng
Created March 13, 2014 02:55

Revisions

  1. jtzeng created this gist Mar 13, 2014.
    24 changes: 24 additions & 0 deletions sample.lisp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    (defun list-sample (lst &optional (amt 1 amt-supplied-p))
    "Choose a random element or n random elements from the collection."
    (labels ((sample-inner (lst amt res)
    (if (not (and lst (plusp amt)))
    (if (and (= (length res) 1) (not amt-supplied-p))
    (car res)
    res)
    (let ((elem (elt lst (random (length lst)))))
    (sample-inner (remove elem lst :count 1) (1- amt)
    (nconc res (list elem)))))))
    (sample-inner lst amt nil)))

    (defun list-sample-test ()
    (setf *random-state* (make-random-state t))
    (format t "~{~a~%~}"
    (list
    (list-sample '(1 2 3))
    (list-sample '(1 2 3) 0)
    (list-sample '(1 2 3) -1)
    (list-sample '(1 2 3) 1)
    (list-sample '(1 2 2 2 2 2 3) 4)
    (list-sample '(1 2 3 4 5 6 7) 10))))

    (list-sample-test)