nupanick

Clojure permutations implementation

Mar 16th, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn drop-nth
  2.   "Removes the nth element from a collection."
  3.   [sqn n]
  4.   (concat (take n sqn) (drop (inc n) sqn)))
  5.  
  6. (defn drop-each
  7.   "Produces a collection of copies of the input, each with a different element removed."
  8.   [sqn]
  9.   (map #(drop-nth sqn %)
  10.        (range (count sqn))))
  11.  
  12. (defn cons-to-all
  13.   "Exactly what it says on the tin."
  14.   [x, sqns]
  15.   (map #(cons x %) sqns))
  16.  
  17. (defn permutations
  18.   "Produces a collection of all possible unique rearrangements of the input sequence."
  19.   ;; FINALLY.
  20.   [sqn]
  21.   (if (= 1 (count sqn))
  22.       #{sqn}
  23.       (reduce into #{}
  24.               (map #(cons-to-all %1 (permutations %2))
  25.                    sqn
  26.                    (drop-each sqn)))))
  27.  
  28. ==================== interactive output ====================
  29.  
  30. mathdice-solver.core=> (permutations [1 2 3])
  31. #{(2 3 1) (1 3 2) (2 1 3) (3 1 2) (1 2 3) (3 2 1)}
  32. mathdice-solver.core=> (permutations [1 2 2])
  33. #{(2 2 1) (2 1 2) (1 2 2)}
  34. mathdice-solver.core=> (permutations [1 1 1])
  35. #{(1 1 1)}
Advertisement
Add Comment
Please, Sign In to add comment