Clojure - list all permutations of a list

Let's say I have a set like this:

#{"word1" "word2" "word3"} 

How can I list all the ways to organize these words, i.e.

 word1 word2 word3 word2 word3 word1 word3 word2 word1 

and etc.

+5
source share
2 answers

The easiest way is math.combinatorics :

 user> (require '[clojure.math.combinatorics :as combo]) nil user> (combo/permutations #{"word1" "word2" "word3"}) (("word1" "word2" "word3") ("word1" "word3" "word2") ("word2" "word1" "word3") ("word2" "word3" "word1") ("word3" "word1" "word2") ("word3" "word2" "word1")) 

Edit: I did not look at the implementation of math.combinatorics, but there was a lazy version, because the OP asked for some kind of code.

 (defn permutations [s] (lazy-seq (if (seq (rest s)) (apply concat (for [xs] (map #(cons x %) (permutations (remove #{x} s))))) [s]))) 
+12
source

Although math.combinatorics is probably the correct answer, I was looking for something simpler. Below is a lazy implementation that I can execute:

 (defn permutations [colls] (if (= 1 (count colls)) (list colls) (for [head colls tail (permutations (disj (set colls) head))] (cons head tail)))) 
+6
source

Source: https://habr.com/ru/post/1203540/


All Articles