3 ms·
Let’s make it a one liner :D fib = Hash.new {|hash, key| hash[key] = key < 2 ? key : hash[key-1] + hash[key-2] } Example: fib[123] # => 2269837405200686395697
by hit8run 3y ago
Let’s make it a one liner :D
fib = Hash.new {|hash, key| hash[key] = key < 2 ? key : hash[key-1] + hash[key-2] }
Example:
fib[123] # => 22698374052006863956975682
Makes use of memoization.
- nix-zarathustra 3y agoYes, I was going off of memory and thought that it was memoising it, but I made a mistake and fixed it. fib = Hash.new do |k, v| next 1 if v == 0 || v == 1 k[v] = k[v-1] + k[v-2] end I like yours better though, it seems a lot simpler with the less than 2 check.