Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all subsets of size N in an array using Ruby

Given an array ['a', 'b', 'c', 'd', 'e', 'f'], how would I get a list of all subsets containing two, three, and four elements?

I'm quite new to Ruby (moving from C#) and am not sure what the 'Ruby Way' would be.

like image 646
KevDog Avatar asked Sep 09 '11 00:09

KevDog


2 Answers

Check out Array#combination

Then something like this:

2.upto(4) { |n| array.combination(n) }
like image 142
basicxman Avatar answered Oct 10 '22 15:10

basicxman


Tweaking basicxman's a little bit:

2.upto(4).flat_map { |n| array.combination(n).to_a }
#=> [["a", "b"], ["a", "c"], ["a", "d"], ..., ["c", "d", "e", "f"]]
like image 32
tokland Avatar answered Oct 10 '22 17:10

tokland