Skip to content

Instantly share code, notes, and snippets.

@HaanstootZA
Created February 13, 2020 13:38
Show Gist options
  • Select an option

  • Save HaanstootZA/65347b9930ab2ae1db0791abb0151c67 to your computer and use it in GitHub Desktop.

Select an option

Save HaanstootZA/65347b9930ab2ae1db0791abb0151c67 to your computer and use it in GitHub Desktop.
An experiment on writing an enumerable implementation of the Fibonacci Principle.
using System.Collections;
using System.Collections.Generic;
namespace Fibonacci
{
public class FibonacciEnumerable : IEnumerable<ulong>
{
public IEnumerator<ulong> GetEnumerator()
{
return new FibonacciEnumerator(zeroValue: 0, firstValue: 1);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public sealed class FibonacciEnumerator : IEnumerator<ulong>
{
private readonly ulong _ZeroValue;
private readonly ulong _FirstValue;
private ulong _Previous;
public ulong Current { get; private set; }
object IEnumerator.Current
{
get => this.Current;
}
public FibonacciEnumerator(ulong zeroValue, ulong firstValue)
{
this._ZeroValue = zeroValue;
this._FirstValue = firstValue;
this._Previous = zeroValue;
this.Current = firstValue;
}
public bool MoveNext()
{
bool canMoveNext;
try
{
this.Current += this._Previous;
this._Previous = this.Current - this._Previous;
canMoveNext = this.Current >= this._Previous && this.Current > 0;
}
catch
{
canMoveNext = false;
}
return canMoveNext;
}
public void Reset()
{
this._Previous = this._ZeroValue;
this.Current = this._FirstValue;
}
public void Dispose()
{
//NOTHING TO DISPOSE
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment