Created
August 30, 2014 14:10
-
-
Save Fhernd/251c36e569c4ce117785 to your computer and use it in GitHub Desktop.
Demostración de la creación de una secuencia a partir de la interfaz genérica IEnumerable<T>.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace Articulos.Cap04.Secuencias | |
{ | |
public sealed class FibonacciPares | |
{ | |
public static void Main() | |
{ | |
foreach (long fibonacci in GeneradorNumeroPares (GeneradorFibonacci(6))) | |
{ | |
Console.WriteLine (fibonacci); | |
} | |
} | |
// Retorna elemento por elemento de la serie Fibonacci | |
// hasta la cantidad especificada en el argumento: | |
private static IEnumerable<long> GeneradorFibonacci(long cantidadSerie) | |
{ | |
// 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 < cantidadSerie; ++i) | |
{ | |
// Retorna el valor actual de la serie Fibonacci: | |
yield return fibAnterior; | |
int fibNuevo = fibAnterior + fibActual; | |
fibAnterior = fibActual; | |
fibActual = fibNuevo; | |
} | |
} | |
// Método que comprueba si los números generados por la serie | |
// Fibonacci son pares: | |
private static IEnumerable<long> GeneradorNumeroPares(IEnumerable<long> fibonaccis) | |
{ | |
foreach (long fibonacci in fibonaccis) | |
{ | |
if ((fibonacci % 2) == 0) | |
{ | |
yield return fibonacci; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment