-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathLazyFibonacciList.cs
More file actions
52 lines (40 loc) · 878 Bytes
/
LazyFibonacciList.cs
File metadata and controls
52 lines (40 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void Main()
{
var fiboList = new LazyFibonacciList();
var list = new List<int>();
// if you don't use Take(), it'll loop infinitely.
foreach (var element in fiboList.Take(10))
{
Console.WriteLine(element);
}
}
public class LazyFibonacciList : IEnumerable<long>
{
public IEnumerator<long> GetEnumerator() => new Enumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
struct Enumerator : IEnumerator<long>
{
public long Current { get; private set; }
private long Last { get; set; }
object IEnumerator.Current => Current;
public void Dispose() { }
public bool MoveNext()
{
if (Current == -1)
Current = 0;
else if (Current == 0)
Current = 1;
else
{
long next = Current + Last;
Last = Current;
Current = next;
}
return true;
}
public void Reset()
{
Current = -1;
}
}
}