Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Created April 5, 2010 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pervognsen/356035 to your computer and use it in GitHub Desktop.
Save pervognsen/356035 to your computer and use it in GitHub Desktop.
(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