#coding exercise
generate Pascal's triangle:
public static List<List<int>> generatePascalTriangle(int n)
{
var ret = new List<List<int>>();
for (int i = 0; i < n; i++)
{
if (i == 0) { ret.Add(new List<int>() { 1 }); continue; }
ret.Add(new List<int>());
ret[i].Add(1);
for (int j = 0; j < ret[i - 1].Count - 1; j++)
ret[i].Add(ret[i - 1][j] + ret[i - 1][j + 1]);
ret[i].Add(1);
}
return ret;
}
static void Main(string[] args)
{
var ret = generatePascalTriangle(11);
foreach (var r in ret)
{
Console.WriteLine();
for (int i = 0; i < r.Count; i++)
{
Console.Write("{0} ", r[i]);
}
Console.WriteLine();
}
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
generate Pascal's triangle:
public static List<List<int>> generatePascalTriangle(int n)
{
var ret = new List<List<int>>();
for (int i = 0; i < n; i++)
{
if (i == 0) { ret.Add(new List<int>() { 1 }); continue; }
ret.Add(new List<int>());
ret[i].Add(1);
for (int j = 0; j < ret[i - 1].Count - 1; j++)
ret[i].Add(ret[i - 1][j] + ret[i - 1][j + 1]);
ret[i].Add(1);
}
return ret;
}
static void Main(string[] args)
{
var ret = generatePascalTriangle(11);
foreach (var r in ret)
{
Console.WriteLine();
for (int i = 0; i < r.Count; i++)
{
Console.Write("{0} ", r[i]);
}
Console.WriteLine();
}
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
No comments:
Post a Comment