Guest User

Untitled

a guest
Oct 20th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. class Fixnum
  2. # fibonacci instance method using loops instead of recursion
  3. # This variation of the fibonacci method uses loops in order to minimize memory usage
  4. def fibonacci
  5. array = [0,1]
  6.  
  7. (2..self).each do
  8. #can be replaced with "2.upto(self) do" as well as "(self-1).times do"
  9. temp = array[0] + array[1]
  10.  
  11. array[0] = array[1]
  12. array[1] = temp
  13. end
  14.  
  15. array[1]
  16. end
  17. end
  18.  
  19.  
  20. # A bug I had while writing this method: I set the variable temp outside of the loop placing it outside the scope of the loop.
  21. # This meant that the temp variable would never change.
  22. # It's the equivalent of having the following code:
  23. # class Fixnum
  24. # def fibonacci
  25. # array = [0,1]
  26. # temp = array[0] + array[1]
  27. # array[0] = array[1]
  28. # array[1] = temp
  29. # array[0] = array[1]
  30. # array[1] = temp
  31. # array[0] = array[1]
  32. # array[1] = temp
  33. # array[0] = array[1]
  34. # array[1] = temp
  35. # array[0] = array[1]
  36. # array[1] = temp
  37. # array[0] = array[1]
  38. # array[1] = temp
  39. # array[0] = array[1]
  40. # array[1] = temp
  41. #
  42. # and so on
  43. # temp NEVER changes. The result is that array goes from [0,1] to [1,1] and then to [1,1] over and over again.
  44. # You take the value 1 from array[1] and place it in array[0] which is already 1 and then place temp which is 1 into array[1] which is already 1.
  45. # Nothing changes after the first iteration.
Add Comment
Please, Sign In to add comment