ruby array element grouping

2019-03-05 18:07发布

问题:

here is the problem

I have an array:

a = [1, 2, 3, 4]

and want to get:

b = [[1, 2, 3], [1, 3, 4], [1, 2, 4], [2, 3, 4]]

what is the best way? thanks!

回答1:

You are looking for all unique sets of 3 elements out of a set of 4.

Use Array#combination method:

a = [1, 2, 3, 4]
b = a.combination(3).to_a

output:

=> [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

More info:

Array#combination
Wikipedia Combination



回答2:

Here would be my first implementation. (But performance suckz i guess)

array = [1,2,­3,4]
b = []
array.each­{|e| c = array­.clone; c.del­ete(e); b << c}
# b.sort!