Created
October 16, 2015 20:07
-
-
Save rpepato/d7fc590dba0d8931f263 to your computer and use it in GitHub Desktop.
Memoization in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'rubygems' | |
| require 'benchmark' | |
| def fibonacci(n) | |
| return n if n <= 1 | |
| fibonacci( n - 1 ) + fibonacci( n - 2 ) | |
| end | |
| @cache = [0,1] | |
| def fibo(n) | |
| return @cache[n] if @cache[n] | |
| @cache[n] = fibo(n-1) + fibo(n-2) | |
| end | |
| @fibos = Hash.new(0) | |
| def count_fibos(n) | |
| @fibos[n] = @fibos[n] + 1 | |
| return n if n <= 1 | |
| count_fibos( n - 1 ) + count_fibos( n - 2 ) | |
| end | |
| puts Benchmark.measure { | |
| puts fibonacci(1) | |
| } | |
| puts Benchmark.measure { | |
| puts fibo(1) | |
| } | |
| count_fibos(5) | |
| p @fibos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment