Find all subsets of size N in an array using Ruby

2019-05-02 15:35发布

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.

2条回答
来,给爷笑一个
2楼-- · 2019-05-02 16:01

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"]]
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-02 16:16

Check out Array#combination

Then something like this:

2.upto(4) { |n| array.combination(n) }
查看更多
登录 后发表回答