Topic: Pascal Triangle Solution


Author: sgermain@bmtlh554.NoSubdomain.NoDomain (Sylvain St.Germain)
Date: 1 Dec 1994 20:17:42 GMT
Raw View
Someone was asking how to get all the numbers of a given line in the
Pascal Trangle.


This is one of the solutions to the Pascal Triangle that may answer
to your question.  It is prbably one of the most eleganr one because of the use
of the recursivity concept.

Giving the triangle (starting at line 0 col 0)

1
1 1
1 2 1
1 3 3 1


the solution of the line 3, col 2 (say (3,2)) must be calculated as the sum of
the solution of (2,1) and (2,2) as the formula of the Pascal Triangle says,
but the solution of (2,1) is (1,0) + (1,1) witch is 2 and so on.
These kind of loop are often solve by recursivity.

To solve by recursivity you must only know the limits of you problem.
The limits of the Pascal Triangle are:

if line == 0 then value = 1
if col == 0 then value = 1
if line == col then value = 1
otherwise
value = value of ((line -1),(col-1)) + value of ((line-1),col)

and, the problem is solve just by miracle, almost nothing to do !!!

Hope that this is clear enough to make you understand the concept.

#include <stdio.h>

// *******************************************************************
// Function that return the value of the Pascal Triangle at the given
// Column and line (both starting at 0 as the array standard in c)
//
int Val(int iLine, int iCol)
{
 if(iLine == 0)
  return 1;
 if(iCol == 0)
  return 1;
 if(iCol == iLine)
  return 1;

 return(Val(iLine-1, iCol-1) + Val(iLine-1, iCol));
}


// *******************************************************************
// Function that return the complete content of a line in the Pascal
// Triangle
//
// Parameters  : int Line Number
//  : array of integer (must be long enough to contain all the line)

void GetTriPascalLine(int iLineNum, int *piResArray)
{
 int iValue;
 for(int c=0; c<=iLineNum; c++)
 {
  iValue = Val(iLineNum ,c);
  piResArray[c] = iValue;
 }
}

#define iResSize 20
#define iNumLine 10
main()
{
 int Results[iResSize];

 // Do it for the 10 first lines
 for(int i=0; i<=iNumLine; i++)
 {
  // Clean the results array
  for(int j=0; j<iResSize; j++) Results[j] = 0;

  // Calculate the line
  GetTriPascalLine(iNumLine, Results);

  // Print it out!!
  for(int k=0; k<iResSize; k++)
   printf("%i ", Results[k]);
  printf("\n");
 }

}


By   : Sylvain St-Germain


Author: sgermain@bmtlh554.NoSubdomain.NoDomain (Sylvain St.Germain)
Date: 1 Dec 1994 21:23:22 GMT
Raw View
Good Solution man...