Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Mar 22 ’12

Using Hash as Recursive Function with Memoization

We can define a new Hash in a smart way by using Hash#new and passing it a block:

h    = Hash.new {|hash,key| hash[key] = hash[key-1] + hash[key-2]}
h[1] = 0
h[2] = 1

puts h[3] #=> 1
puts h[100] #=> 218922995834555169026

Here an example of famous Collatz Conjecture:

h    = Hash.new {|hash,n| hash[n] = 1 + (n.odd? ? hash[3*n+1] : hash[n/2])}
h[1] = 1

puts h[100] #=> 26
puts h[1000] #=> 112

via: thoughbot’s blog

4 notes 0 comments

  1. fenprace-blog-blog reblogged this from rubyquicktips
  2. rmdhn-blog submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus