Generating Combinations with Ruby and Recursion
September 16th, 2009
Hello fellow Rubyists
The following code is a recursive combination generator written in Ruby. Given an array of objecs/numbers/..etc, it will return an array of all possible combinations . This originally started out using two functions that contained looping logic in them. It worked well, however I just wanted to stretch myself a bit and try my hand at doing it recursively. Below is the result of my efforts. I hope this helps with anything you may be working on… enjoy!
#javazquez.com
#tail is a clone because of Ruby's passing by reference and shift
#returns an unsorted array
def combination(ary,head=[])
return ary if(ary==[] )
head << ary.shift
tail = ary.clone
tmp=[]
if(tail.length>=1)
tmp+= combination(tail[1..(tail.length)],head.flatten)+
combination(Array(tail[-1]),head.flatten)
tmp+=combination(tail[2..(tail.length)],head.flatten) if(tail[2])
else
tmp += combination(tail,Array(head[0]))
end
tmp += combination(tail, []) +combination(ary,head.flatten)
return (tmp << head).uniq
end
combination([1,2,3,4]).sort.each{|it| puts it.inspect }
# combination(['A','B','C','D','E','F','G','H','I','J']).sort.each{|it| puts it.inspect}
# combination(['A','B','C','D']).sort.each{|row| puts row.inspect}
----output--
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 4]
[1, 3]
[1, 3, 4]
[1, 4]
[2]
[2, 3]
[2, 3, 4]
[2, 4]
[3]
[3, 4]
[4]