Created
September 11, 2012 13:34
-
-
Save orend/3698516 to your computer and use it in GitHub Desktop.
memoization using a hash. from rubies in the rough
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
| def fibonacci(nth, series = method(:fibonacci)) | |
| if nth < 2 | |
| nth | |
| else | |
| series[nth - 2] + series[nth - 1] | |
| end | |
| end | |
| # The easiest memoization in the world: | |
| fibs = Hash.new { |series, nth| series[nth] = fibonacci(nth, series) } | |
| p fibs[100] | |
| # put diffrently: | |
|  fibonacci = Hash.new { |numbers, index| | |
| numbers[index] = fibonacci[index - 2] + fibonacci[index - 1] | |
| }.update(0 => 0, 1 => 1) | |
| p fibonacci[300] | |
| # 222232244629420445529739893461909967206666939096499764990979600 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment