Created
September 21, 2017 17:19
-
-
Save noprompt/3c485ec493bd7047f364a012ec6b39dd to your computer and use it in GitHub Desktop.
Permutations in Clojure (based on Heap's algorithm)
This file contains hidden or 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 swap | |
"Swap the elements at positions `i` and `j` in `v`." | |
{:private true} | |
[v i j] | |
(-> v | |
(assoc i (get v j)) | |
(assoc j (get v i)))) | |
;; SEE: https://en.wikipedia.org/wiki/Heap%27s_algorithm | |
(defn permutations [coll] | |
(let [v (vec coll) | |
n (count v)] | |
(loop [n n | |
a [v]] | |
(if (zero? n) | |
a | |
(let [n* (dec n) | |
a* (mapcat | |
(fn step [v] | |
(map | |
(fn [i] | |
(swap v i n*)) | |
(range n))) | |
a)] | |
(recur n* a*)))))) |
Author
noprompt
commented
Sep 21, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment