[bmx]Iterate through Fibonacci sequence using For/EachIn

Started by TomToad, April 03, 2018, 18:33:40

Previous topic - Next topic

TomToad

Title:Fibonacci Sequence
Author: TomToad
Posted: Apr 3,2018

Wasn't sure to post this in Algorithms or Miscellaneous.  Chose to put it here in algorithms.  This is an enumerator for EachIn that returns the next number in the Fibonacci sequence.  As EachIn can only return Objects, the Int type has to be boxed into a TInt object.  To use, just type For Local i:TInt = EachIn Fibonacci(num) where num is however many numbers you want returned. i.e. Fibonacci(10) will iterate through the first 10 numbers.
Code (blitzmax) Select
SuperStrict

Type TInt
Field value:Int

Function Create:TInt(value:Int)
Local i:TInt = New TInt
i.value = value
Return i
End Function
End Type

Type TFibonacci
Field count:Int = 0
Field MaxCount:Int = 0
Field Last:Int = 0
Field Total:Int = 0

Method HasNext:Int()
If count < MaxCount Then Return True
Return False
End Method

Method NextObject:Object()
If Total = 0
Total = 1
Else
Total :+ Last
Last = Total - Last
End If
count :+ 1
Return TInt.Create(Total)
End Method

Method ObjectEnumerator:TFibonacci()

Return Self
End Method

End Type

Function Fibonacci:TFibonacci(num:Int = 10)
Local Fib:TFibonacci = New TFibonacci
Fib.MaxCount = num
Return Fib
End Function

For Local i:TInt = EachIn Fibonacci(12)
Print i.value
Next

------------------------------------------------
8 rabbits equals 1 rabbyte.