Skip to content

Instantly share code, notes, and snippets.

@sbocq
Last active February 21, 2021 11:45
Show Gist options
  • Save sbocq/f50d3641d2554799e97964a56a0becd4 to your computer and use it in GitHub Desktop.
Save sbocq/f50d3641d2554799e97964a56a0becd4 to your computer and use it in GitHub Desktop.
Compute all permutations of a collection in Clojure (non-lazy, iterative)
(defn permutations [coll]
(letfn [(rotations [c vs] (reduce (fn [rotations _]
(conj rotations
(let [[head & tail] (peek rotations)]
(conj (vec tail) head))))
[(conj vs c)]
vs))]
(cond-> (reduce (fn [permutations c] (mapcat (partial rotations c) permutations))
[[]]
coll)
(not (or (set? coll) (apply distinct? coll))) distinct)))
;; Examples
;; > (permutations [1 2 3])
;;([1 2 3] [2 3 1] [3 1 2] [2 1 3] [1 3 2] [3 2 1])
;; > (permutations [1 1 3])
;;([1 1 3] [1 3 1] [3 1 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment