Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Created November 21, 2018 10:49
Show Gist options
  • Save harrisonmalone/f7c5fa77ec70c877d9897c4ce113ae6e to your computer and use it in GitHub Desktop.
Save harrisonmalone/f7c5fa77ec70c877d9897c4ce113ae6e to your computer and use it in GitHub Desktop.
def fibonacci(n, arr)
a = 0
b = 1
n.times do
temp = a
# sets temp to be 0, 1 on the second loop
a = b
# sets b to be 1, still 1 on the second loop, 2 on the third loop
b = temp + b
arr << a
# b = 0 + 1, gives you 1, same on the second loop, 1 + 1 on the third loop
end
return arr
end
p fibonacci(20, [])
n1 = 0
n2 = 1
arr = []
while arr.length < 20
temp = n1
# here we need a temporary variable to store the value of n1, this is because we have to reassign the variable n1 but we don't want to lose its value
n1 = n2
# here we get the value we need to push into our array
arr << n1
n2 = n2 + temp
# here we add the value of temp with n2 to increment, remember that a fibonacci number is the previous two numbers in the cycle added togther
end
# here i'm using the fibonacci method in two different ways
# one way uses times and one way uses a while loop and ends when the array is a certain length
# nice way to see why we need to reassign sometimes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment