My name is MatthewRudy, and I'm a Rails Developer. I am.... MATTHEW RUDY ON RAILS!!!


Silly combinations thing

Yeah,
someone asked "how can I get all the combinations of an array?" on Rails-Talk, and I was bored at work, so I played around.

Here's what I got;


def combinations(array)
return [] if array == []
return [array, []] if array.length == 1

# split [1,2,3] => [1], [2,3]
left, right = array[0..0], array[1..-1]
rtn = []

combinations(right).each do |r_array|
rtn << r_array
rtn << left + r_array
end

return rtn
end

>> combinations([1])
=> [[1], []]
>> combinations([1,2])
=> [[2], [1, 2], [], [1]]
>> combinations([1,2,3])
=> [[3], [1, 3], [2, 3], [1, 2, 3], [], [1], [2], [1, 2]]

Perhaps it could be re-written to order them more nicely.
(I like the ordering: [], [1], [2], [3], [1,2], [1,3] ... but who can really complain)