Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure: permutations of subsets?

Tags:

set

clojure

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?

like image 563
Abe Avatar asked Dec 27 '22 08:12

Abe


1 Answers

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.

like image 177
Blacksad Avatar answered Jan 03 '23 10:01

Blacksad