Created
February 28, 2018 02:19
-
-
Save Fhernd/13585278ac8a07dd03e3a2086cf1b4ff to your computer and use it in GitHub Desktop.
Generar triángulo de Pascal en C# usando LINQ.
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
// Valores iniciales del triángulo de Pascal: | |
List<Tuple<int, int, int>> trianguloPascal = new List<Tuple<int, int, int>>(); | |
// Primera fila: | |
// 1 | |
trianguloPascal.Add(new Tuple<int, int, int>(1, 1, 1)); | |
// Segunda fila: | |
// 1 | |
//1 1 | |
trianguloPascal.Add(new Tuple<int, int, int>(2, 1, 1)); | |
trianguloPascal.Add(new Tuple<int, int, int>(2, 2, 1)); | |
// Se generarán 12 filas: | |
for(int i = 1; i <= 10; ++i) | |
{ | |
// Calcula la fila y columna actuales: | |
int filaActual = trianguloPascal.Last().Item1 + 1; | |
int columnaActual = trianguloPascal.Last().Item2 + 1; | |
// Genera los valores de la siguiente fila: | |
for(int j = 1; j <= columnaActual; ++j) | |
{ | |
// Comprueba se trata de la primera y última columna | |
// para agregar un 1: | |
if(j == 1 || j == columnaActual) | |
{ | |
trianguloPascal.Add(new Tuple<int, int, int>(filaActual, j, 1)); | |
} | |
else | |
{ | |
// Cálculo del nuevo valor: | |
int nuevoValor = trianguloPascal.First(v => v.Item1 == (filaActual - 1) && v.Item2 == (j - 1)).Item3 | |
+ trianguloPascal.First(v => v.Item1 == (filaActual - 1) && v.Item2 == j).Item3; | |
trianguloPascal.Add(new Tuple<int, int, int>(filaActual, j, nuevoValor)); | |
} | |
} | |
} | |
// Muestra los valores del triángulo de Pascal: | |
trianguloPascal.ToLookup(t => t.Item1, t => t.Item3.ToString()) | |
.Select(t => t.Aggregate((x, y) => x + " " + y)) | |
.Aggregate((u, v) => u + Environment.NewLine + v) | |
.Dump("Triángulo de Pascal"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment