Monday, August 18, 2014

Combinations + recursion

In the previous blog entry, I've posted two iterative solutions for creating combinations using NetLogo and Ruby. I then spent an entire weekend trying to conquer recursion and to re-write this function using recursive methods. I think I am still a bit away from being truly conformable with implementing recursion: each time I think I understand its implementation, I find that I still do not understand it. I guess, it is a recursive process in itself; I just need to get a proper base case.

Anyway, this blog post has tremendously helped me to get a firmer grasp of both the concept and implementation details. I particularly liked different examples ranging from simple to complex. I then implemented the fill algorithm trying my hardest not to look for hints.

Below are the fruits of my weekend fight with combinations:

def combinations(str)
    return [str] if str.length == 1
    combos = combinations(str[1..-1])
    current = [str[0]]
    combos.each {|combo| current += [str[0] + combo] }
    return (current + combos)
end  

No comments :

Post a Comment