Skip to content

Instantly share code, notes, and snippets.

@AbdulR3hman
Last active August 29, 2015 14:24
Show Gist options
  • Save AbdulR3hman/e20c6d0b4a90b2165634 to your computer and use it in GitHub Desktop.
Save AbdulR3hman/e20c6d0b4a90b2165634 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Public: Calculates the nth Fibonacci number using either a memoized or
# non-memoized functionality
#
# Examples
#
# fib = Fibonacci.new
# fib.get_fib 10
# # => 55
class Fibonacci
# Public: Initialize the array of fibonacci numbers for the memoized
# implementation
def initialize
# We must start the fib_array with 0 because the index of the number
# represents the nth fibonacci number, and there is no 0th fibonacci number
@fib_array = [0, 1]
end
# Public: A memoized implementation of calcutating a fibonacci number
#
# n - the fibonacci number to be calculated
#
# Examples
#
# fib = Fibonacci.new
# fib.get_fib 7
# # => 13
def get_fib(n)
return @fib_array[n] unless @fib_array[n].nil?
fib_value = get_fib(n - 1) + get_fib(n - 2)
@fib_array.push fib_value
fib_value
end
# Public: A non-memoized implementation of calcutating a fibonacci number
#
# n - the fibonacci number to be calculated
#
# Examples
#
# fib = Fibonacci.new
# fib.get_fib_old 7
# # => 13
def get_fib_old(n)
return n if n < 2
get_fib_old(n - 1) + get_fib_old(n - 2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment