October 28, 2020, 11:39:40 PM

### Author Topic: [bmx]Iterate through Fibonacci sequence using For/EachIn  (Read 1162 times)

#### TomToad

• Hero Member
• Posts: 517
##### [bmx]Iterate through Fibonacci sequence using For/EachIn
« on: April 03, 2018, 06:33:40 PM »
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
1. SuperStrict
2.
3. Type TInt
4.         Field value:Int
5.
6.         Function Create:TInt(value:Int)
7.                 Local i:TInt = New TInt
8.                 i.value = value
9.                 Return i
10.         End Function
11. End Type
12.
13. Type TFibonacci
14.         Field count:Int = 0
15.         Field MaxCount:Int = 0
16.         Field Last:Int = 0
17.         Field Total:Int = 0
18.
19.         Method HasNext:Int()
20.                 If count < MaxCount Then Return True
21.                 Return False
22.         End Method
23.
24.         Method NextObject:Object()
25.                 If Total = 0
26.                         Total = 1
27.                 Else
28.                         Total :+ Last
29.                         Last = Total - Last
30.                 End If
31.                 count :+ 1
32.                 Return TInt.Create(Total)
33.         End Method
34.
35.         Method ObjectEnumerator:TFibonacci()
36.
37.                 Return Self
38.         End Method
39.
40. End Type
41.
42. Function Fibonacci:TFibonacci(num:Int = 10)
43.         Local Fib:TFibonacci = New TFibonacci
44.         Fib.MaxCount = num
45.         Return Fib
46. End Function
47.
48. For Local i:TInt = EachIn Fibonacci(12)
49.         Print i.value
50. Next
51.
52.
------------------------------------------------
8 rabbits equals 1 rabbyte.

SimplePortal 2.3.6 © 2008-2014, SimplePortal