CC-17 : Generate Pascal’s Triangle.
Description:
Pascal’s triangle consists of rows of integers formatted to be displayed as a triangle. In rows of the triangle, the first and last elements are always 1. The other elements in rows (other than first and last) are sum of elements directly above it in previous row. Given input integer reqRows, generate and return a Pascals triangle with that may rows multidimensional int array.
Test cases and expected outputs:
| Input | Expected outputs |
|---|---|
| reqRows=3 | 1 1 1 1 2 1 |
| reqRows=4 | 1 1 1 1 2 1 1 3 3 1 |
| reqRows=5 | 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 |
Pseudocode:
| The java method should accept following input parameters: int reqRows. |
| Declare a multidimensional array pTriangle with reqRows rows and undeclared columns. |
| Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Declare pTriangle[rIdx] row to be an int array with rIdx+1 rows.
o Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If cIdx is first or last column of current row, set current element to 1 using pTriangle[rIdx][cIdx]=1.
Else set current element to sum of numbers above it using pTriangle[rIdx][cIdx]=pTriangle[rIdx-1][cIdx]+pTriangle[rIdx-1][cIdx-1].
Print the value of pTriangle[rIdx][cIdx].
|
| After above loops are completed, pTriangle contains the generated Pascals triangle with required number of rows. Return pTriangle. |
Code:
public int[][] matPascalTriangle(int reqdRows) throws Exception{
int[][] pTri = new int [reqdRows][];
for (int rIdx=0; rIdx < reqdRows; rIdx++) {
pTri[rIdx]=new int[rIdx+1];
System.out.print("\n");
for (int cIdx=0; cIdx < pTri[rIdx].length; cIdx++){
if ((rIdx-1 <0)|| (cIdx-1<0) || (cIdx>=pTri[rIdx-1].length)) {
pTri[rIdx][cIdx]=1;
}else {
pTri[rIdx][cIdx]=pTri[rIdx-1][cIdx]+pTri[rIdx-1][cIdx-1];
}
System.out.print(pTri[rIdx][cIdx]);
System.out.print(" ");
}
}
return pTri;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |