Abe
Abe

Reputation: 24008

clojure: permutations of subsets?

I'm new to clojure, looking for a function to generate permutations of subsets:

=> (find-subsets 1 #{1 2 3 4})
(#{1} #{2} #{3} #{4})

=> (find-subsets 2 #{1 2 3 4})
(#{1 2} #{1 3} #{1 4} #{2 3} #{2 4} #{3 4})

=> (find-subsets 3 #{1 2 3 4})
(#{1 2 3} #{1 3 4} #{2 3 4})

Does such a thing exist? If not, is there a nice, clean, idiomatic way to code the function?

Upvotes: 4

Views: 2107

Answers (1)

Blacksad
Blacksad

Reputation: 15442

Take a look at combinatorics. It does what you need:

; all the unique ways of taking n different elements from items
(clojure.math.combinatorics/combinations [1 2 3] 2)
;;=> ((1 2) (1 3) (2 3))

If it complains because you use a set instead of a vector, just convert to vector with vec before calling combinations.

Upvotes: 10

Related Questions