I'm trying to create a function that, given a row and column, will calculate the value at that position in Pascal's Triangle.
Example:
val = GetPasVal(3, 2); // returns 2
So here I'm specifying row 3, column 2, which as you can see:
1
1 1
1 2 1
...should be a 2.
The Pascal's triangle contains the Binomial Coefficients C(n,k); There is a very convenient recursive formula
C(n, k) = C(n-1, k-1) + C(n-1, k)
You can use this formula to calculate the Binomial coefficients.
Using Armen's equation the recursive code for implementing pascals triangle will be like below:
using System;
using System.Collections.Generic;
public class Program
{
public void Main()
{
for(int i =0 ; i<5;i++)
{
int sum = 1;
Console.WriteLine();
for(int j =0 ; j<=i;j++)
{
Console.Write(pascal(i,j));
//Console.Write(sum); //print without recursion
sum= sum *(i-j) / (j + 1);
}
}
}
public int pascal(int x, int y)
{
if((x+1)==1 || (y+1)==1 || x==y)
{
return 1;
}
else
{
return pascal(x-1,y-1)+ pascal(x-1,y);
}
}
}
for row in range(10):
print('{: ^45}'.format(' '.join(str(pascal(row, col)) for col in range(row+1))))
Use the above code to print out your pascal triangle and thereby modify the code. The first 10 should look like:
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
The GetPasVal method will calculate all the numbers in the Pascal's Triangle up to the point that you will give (height) and after that the method will return the value of the index on that row(width). This is something you can use. It's quite simple. You just have to use a jagged array.
static void Main(string[] args)
{
var x = GetPasVal(3, 2);
Console.WriteLine(x);
}
public static long GetPasVal(int height, int width)
{
long[][] triangle = new long[height][];
for (int i = 0; i < height; i++)
{
triangle[i] = new long[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
if (i >= 2)
{
for (int j = 1; j < i; j++)
{
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
}
return triangle[height - 1][width - 1];
}
There is a formula from Combinations for working out the value at any place in Pascal's triangle:
It is commonly called n choose k
and written like this:
n choose k = n! / k!(n-k)!
Notation: n choose k
can also be written C(n,k)
, nCk
.
static void Main(string[] args)
{
var x = GetPasVal(3, 2);
Console.WriteLine(x);
}
public static long GetPasVal(int row, int col)
{
int factOfRow = 1,i;
for(i = 1;i<=(row - 1);i++)
factOfRow *= i;
int factOfRowMinusCol = 1;
for(i = 1;i<=(row - 1)- (col - 1);i++)//check out below link to understand condition
factOfRowMinusCol *= i;
int factOfCol = 1;
for(i = 1;i<= (col - 1);i++)
factOfCol *=i;
int fact = factOfRow / (factOfCol * factOfRowMinusCol);
return fact;
}
来源:https://stackoverflow.com/questions/15601867/how-can-i-calculate-the-number-at-a-given-row-and-column-in-pascals-triangle