using System;
using System.Collections.Generic;
namespace Articulos.Cap04.Iteradores
{
public sealed class IteradorSerieFibonacci
{
public static void Main()
{
// El iterador se encarga de recorrer cada elemento
// generado por el método `Fibonacci`:
foreach (int fib in Fibonacci(7))
{
Console.Write ("{0} ", fib.ToString() );
}
Console.WriteLine ();
}
// Retorna elemento por elemento de la serie Fibonacci
// hasta la cantidad especificada en el argumento:
private static IEnumerable<int> Fibonacci(int numero)
{
// Por cada iteración retorna el valor de la serie actual,
// realiza los cálculos necesarios para generar el siguiente
// valor de la serie:
for (int i = 0, fibAnterior = 1, fibActual = 1; i < numero; ++i)
{
// Retorna el valor actual de la serie Fibonacci:
yield return fibAnterior;
int fibNuevo = fibAnterior + fibActual;
fibAnterior = fibActual;
fibActual = fibNuevo;
}
}
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYzsKCm5hbWVzcGFjZSBBcnRpY3Vsb3MuQ2FwMDQuSXRlcmFkb3Jlcwp7CiAgICBwdWJsaWMgc2VhbGVkIGNsYXNzIEl0ZXJhZG9yU2VyaWVGaWJvbmFjY2kKICAgIHsKICAgICAgICBwdWJsaWMgc3RhdGljIHZvaWQgTWFpbigpCiAgICAgICAgewogICAgICAgICAgICAvLyBFbCBpdGVyYWRvciBzZSBlbmNhcmdhIGRlIHJlY29ycmVyIGNhZGEgZWxlbWVudG8gCiAgICAgICAgICAgIC8vIGdlbmVyYWRvIHBvciBlbCBtw6l0b2RvIGBGaWJvbmFjY2lgOgogICAgICAgICAgICBmb3JlYWNoIChpbnQgZmliIGluIEZpYm9uYWNjaSg3KSkKICAgICAgICAgICAgewogICAgICAgICAgICAgICAgQ29uc29sZS5Xcml0ZSAoInswfSAiLCBmaWIuVG9TdHJpbmcoKSApOwogICAgICAgICAgICB9CiAgICAgICAgICAgIAogICAgICAgICAgICBDb25zb2xlLldyaXRlTGluZSAoKTsKICAgICAgICB9CiAgICAgICAgCiAgICAgICAgLy8gUmV0b3JuYSBlbGVtZW50byBwb3IgZWxlbWVudG8gZGUgbGEgc2VyaWUgRmlib25hY2NpIAogICAgICAgIC8vIGhhc3RhIGxhIGNhbnRpZGFkIGVzcGVjaWZpY2FkYSBlbiBlbCBhcmd1bWVudG86CiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgSUVudW1lcmFibGU8aW50PiBGaWJvbmFjY2koaW50IG51bWVybykKICAgICAgICB7CiAgICAgICAgICAgIC8vIFBvciBjYWRhIGl0ZXJhY2nDs24gcmV0b3JuYSBlbCB2YWxvciBkZSBsYSBzZXJpZSBhY3R1YWwsIAogICAgICAgICAgICAvLyByZWFsaXphIGxvcyBjw6FsY3Vsb3MgbmVjZXNhcmlvcyBwYXJhIGdlbmVyYXIgZWwgc2lndWllbnRlIAogICAgICAgICAgICAvLyB2YWxvciBkZSBsYSBzZXJpZToKICAgICAgICAgICAgZm9yIChpbnQgaSA9IDAsIGZpYkFudGVyaW9yID0gMSwgZmliQWN0dWFsID0gMTsgaSA8IG51bWVybzsgKytpKQogICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAvLyBSZXRvcm5hIGVsIHZhbG9yIGFjdHVhbCBkZSBsYSBzZXJpZSBGaWJvbmFjY2k6CiAgICAgICAgICAgICAgICB5aWVsZCByZXR1cm4gZmliQW50ZXJpb3I7CiAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgIGludCBmaWJOdWV2byA9IGZpYkFudGVyaW9yICsgZmliQWN0dWFsOwogICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICBmaWJBbnRlcmlvciA9IGZpYkFjdHVhbDsKICAgICAgICAgICAgICAgIGZpYkFjdHVhbCA9IGZpYk51ZXZvOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgfQp9