Created
April 5, 2010 04:49
-
-
Save pervognsen/356035 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn rand-range [m n] | |
(+ m (rand-int (- n m)))) | |
(defn with-transient [x f] | |
(persistent! (f (transient x)))) | |
(defn swap-entries! [x i j] | |
(assoc! x i (x j) j (x i))) | |
(defn knuth-shuffle [xs] | |
(let [n (count xs), rand-index #(rand-range % n)] | |
(with-transient (vec xs) | |
(fn [v] (reduce #(swap-entries! %1 %2 (rand-index %2)) v (range n)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment