Skip to content

Instantly share code, notes, and snippets.

@Kallin
Created March 22, 2016 21:39
Show Gist options
  • Save Kallin/e6d966e5311afd69de50 to your computer and use it in GitHub Desktop.
Save Kallin/e6d966e5311afd69de50 to your computer and use it in GitHub Desktop.
adnan's a fibber
@fibs = {
0 => 0,
1 => 1,
}
def fib(n)
cached_result = @fibs[n]
return cached_result if cached_result
new_result = fib(n-1) + fib(n-2)
@fibs[n] = new_result
new_result
end
fib(100)
@fibs.values.each { |n| puts n }
@thisduck
Copy link

def fib(n)
  result = [0, 1]
  (3..n).each do
    result << result[-1] + result[-2]
  end
  result.first(n)
end

@Kallin
Copy link
Author

Kallin commented Mar 22, 2016

clever, but why result.first(n) and not just result?

@NatMorcos
Copy link

@Kallin first(n) because if n = 0 or n = 1 you don't want to just return result = [0,1] because that's the first two numbers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment