开发者

Find all subsets of size N in an array using Ruby

开发者 https://www.devze.com 2023-04-03 11:57 出处:网络
Given an array [\'a\', \'b\', \'c\', \'d\', \'e\',开发者_开发问答 \'f\'], how would I get a list of all subsets containing two, three, and four elements?

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.


Check out Array#combination

Then something like this:

2.upto(4) { |n| array.combination(n) }


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"]]
0

精彩评论

暂无评论...
验证码 换一张
取 消