Monday 22 December 2008

99 Problems in Lisp (Part VIII)

P26 - Generating the combinations of K distinct objects chosen from N.


(defn append-prefix [prefix lst-elements]
(mapcat (fn [x] (list (concat prefix (list x)))) lst-elements))

(defn combination [n lst]
(if (> n (count lst))
nil
(let [elem-list (split lst (dec n)) rlist (nthrest lst (dec n))]
(concat (append-prefix (first elem-list) rlist) (combination n (rest lst))))))


Only two left and I've done the lists part....

No comments:

Post a Comment