Sunday, 21 December 2008
99 Problems in Lisp (Part VII)
P23 - Extract a given number of randomly selected elements from a list. This is daft looking because the previously defined
P24 Select N different frombers from the set 1..m
P25 Permute a list
remove-at
function is one based!
(defn rnd-select [lst n]
(when (> n 0)
(let [x (rand-int (count lst))]
(lazy-cons (nth lst x) (rnd-select (remove-at lst (inc x)) (dec n))))))
P24 Select N different frombers from the set 1..m
(defn lotto-select [n rng]
(rnd-select (range 1 rng) n))
P25 Permute a list
(defn rnd-permu [lst]
(let [length (count lst)]
(when (> length 0)
(let [x (rand-int length)]
(lazy-cons (nth lst x) (rnd-permu (remove-at lst (inc x))))))))
Labels: clojure
Subscribe to Posts [Atom]