The seq-utils library has a shuffle function that calls out to
java.util.Collections.

If you want to do it yourself, the easiest would be

(defn naive-shuffle [xs]
  (let [v (vec xs)]
    (->> (count v) range lex-permutations rand-elt (map v))))

This uses the seq-utils and combinatorics libraries from clojure.contrib.

However, generating all permutations obviously doesn't scale beyond a
couple of elements. For that you will need a real algorithm like the
Knuth shuffle:

(defn swap-elts [x i j]
  (assoc x i (x j) j (x i)))

(defn rand-range
  ([n] (rand-int n))
  ([m n] (+ m (rand-int (- n m)))))

(defn knuth-shuffle [xs]
  (let [v (vec xs)]
    (reduce #(swap-elts %1 %2 (rand-range %2 (count %1))) v (range (count v)))))

-Per

On Mon, Apr 5, 2010 at 3:14 AM, Linus Ericsson
<[email protected]> wrote:
> Hello Clojure!
>
> Is there any straight-forward way to randomly reorder a list?
>
> ie:
>
> (randomize-list (list 1 2 3 4))
> -> (3 2 1 4)
>
> Regards,
> Linus Ericsson
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected]
> Note that posts from new members are moderated - please be patient with your
> first post.
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

To unsubscribe, reply using "remove me" as the subject.

Reply via email to