Saturday, February 22, 2014

99 Clojure Problems – 23: Extract a Given Number of Randomly Selected Elements From a List


(deftest p23-random-select
  (is (= 3 (count (random-select 3 '(1 2 3 4 5 6))) )))


There is a simple and idiomatic solution to this problem based on shuffle (which delegates to java.util.Collections#shuffle).

I did another implementation based on recursive loop'ing and the Clojure's rand function (which delegates to java.lang.Math#random). The basic idea is to remove a randomly selected element (reusing remove-at from problem 20) and repeat the process n times. The recipe is fairly simple: use a loop binding with the function parameters and an aggregator. Remove the random element. Then destructure the result, cons'ing the removed element onto the result aggregator and passing the remaining elements into the recur call. Decrement n with each recursion. Exit at (= 0 n).

Read more about this series.

No comments: