-11

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.

Community
  • 1
  • 1
user2205090
  • 33
  • 1
  • 1
  • 3

5 Answers5

9

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.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • I am sorry but I didn't understand :( can you show me the code please? – user2205090 Mar 24 '13 at 18:11
  • I would use the usual direct formula given in the section [#Multiplicative formula](http://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula) in the same article. Can easily be implemented with one or two `for` loops. Decide if you want to use integer or floating-point arithmetic for the calculation. They have different limitations. – Jeppe Stig Nielsen Mar 24 '13 at 18:47
  • @JeppeStigNielsen: The problem with the multiplicative formula is that intermediate results may not be storable in your destination type whereas the final reault is. That needs additional care. – Armen Tsirunyan Mar 24 '13 at 18:56
  • Agree. You should probably use the formula `C(n, k) == ( n*(n-1)*(n-2)*... )/( k*(k-1)*(k-2)*... )` where both the numerator and the denominator have `k` factors. If you calculate the entire numerator first with an integer type (possibly `BigInteger`) by a `for` loop, then the eventual division will be exact, of course. – Jeppe Stig Nielsen Mar 25 '13 at 08:29
  • Now I found the blog post [Calculate the binomial coefficient "N choose K" efficiently in C#](http://blog.csharphelper.com/2010/01/14/calculate-the-binomial-coefficient-n-choose-k-efficiently-in-c.aspx) where they note that if you take the product `(n/k) * ((n-1)/(k-1)) * ((n-2)/(k-2)) * ...` (with `k` factors), and evaluate it ***from the right (backwards)***, then every result along the way will be an exact integer. So that's kind of beautiful. The recursive method is also beautiful, of course, and really short, but I don't know how well the runtime will handle it for big `n` values. – Jeppe Stig Nielsen Mar 25 '13 at 08:48
  • @JeppeStigNielsen: If memorization is employed along with recursion, the recursive formula performs really well – Armen Tsirunyan Mar 25 '13 at 08:52
  • That blog post is equivalent to the recursive formula `C(n, k) == C(n-1, k-1) * n / k` which also uses integers along the way, and which is a "singly" recursive formula where `C(·, ·)` appears only once on the right-hand side. – Jeppe Stig Nielsen Mar 25 '13 at 09:07
  • @JeppeStigNielsen: Again, the problem with that is that since either n or C(n-1, k - 1) is not necessarily divisible by k, you will have to first multiply C(n-1, k-1) with n and then define the result by k. By the product may overflow, whereas after division it would be a nice whole number that fits into your type. – Armen Tsirunyan Mar 25 '13 at 09:12
  • Thanks you all but that's what I did: int get_pascal(const int row_no,const int col_no) { if (row_no == 0 || row_no == 1 || col_no == 0 || col_no == row_no) { return 1; } return(get_pascal(row_no-1,col_no-1)+get_pascal(row_no-1,col_no)); } and it's work.. – user2205090 Mar 25 '13 at 12:27
  • @user2205090: Good, you used the recursive formula. It's not terribly efficient unless you store all the intermediate results (in a 2D array, for example) and avoid recalculating the same thing over and over again. – Armen Tsirunyan Mar 25 '13 at 12:30
3

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);
    }
  }
}
Pratik
  • 1,472
  • 7
  • 20
  • 36
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://www.mathsisfun.com/pascals-triangle.html

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
0
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         
narcissus789
  • 166
  • 12
0

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];
    }
VG98
  • 114
  • 1
  • 12