(defun shuffle-vector (v) "Return copy of vector with elements shuffled like a deck of cards." (loop with result = (copy-seq v) finally (return result) for i from (length v) downto 1 as j = (random i) do (rotatef (svref result j) (svref result (1- i)))))
That was fun.
I like having both destructive and non-destructive versions:
(defun shuffle-vector (v) "Return copy of vector with elements shuffled like a deck of cards." (shuffle-vector! (copy-seq v)))
(defun shuffle-vector! (result) "Destructively shuffle elements in a vector like a deck of cards." (loop finally (return result) for i from (length result) downto 1 as j = (random i) do (rotatef (svref result j) (svref result (1- i)))))
On Jun 24, 2004, at 10:03 AM, Ben Hyde wrote:
(defun shuffle-vector (v) "Return copy of vector with elements shuffled like a deck of cards." (loop with result = (copy-seq v) finally (return result) for i from (length v) downto 1 as j = (random i) do (rotatef (svref result j) (svref result (1- i)))))
That was fun.
Small-cl-src mailing list Small-cl-src@hexapodia.net http://www.hexapodia.net/mailman/listinfo/small-cl-src