This is my attempt to implement the Pascal Triangle in C#. It is meant to calculate and return a pascal triangle of size n
(which it takes is through the parameter rows
).
static List<List<int>> GetPascalTriangle(int rows)
{
List<List<int>> result = new List<List<int>>();
for (int x = 0; x <= rows - 1; x++)
{
if (x == 0 || x == 1)
{
result.Add(Enumerable.Repeat(1, x + 1).ToList());
}
else
{
List<int> prevRow = result[x - 1];
List<int> semiResult = new List<int>();
semiResult.Add(1);
for (int x1 = 0; x1 <= prevRow.Count - 2; x1++)
{
semiResult.Add(prevRow[x1] + prevRow[x1 + 1]);
}
semiResult.Add(1);
result.Add(semiResult);
}
}
return result;
}
I feel this code is a little messy. Thus I seek some opinion on it and ways to improve it.