Last active
February 21, 2021 11:45
-
-
Save sbocq/f50d3641d2554799e97964a56a0becd4 to your computer and use it in GitHub Desktop.
Compute all permutations of a collection in Clojure (non-lazy, iterative)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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