How to program Pascal's Triangle in Javascript - confusion re Arrays

Robin Andrews picture Robin Andrews · Jun 24, 2015 · Viewed 15.1k times · Source

I'm having a little trouble with my attempt at this problem. Code Below:

function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
    for (var col = 1; col <= row; col++){
        result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
    }
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
    document.write(result[i]+"<br>");
}

It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"

I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo" which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.

Any help with clearing up my misconceptions appreciated.

Answer

Akash Kriplani picture Akash Kriplani · Jun 7, 2017

The Pascal's Triangle can be printed using recursion

Below is the code snippet that works recursively.

We have a recursive function pascalRecursive(n, a) that works up till the number of rows are printed. Each row is a element of the 2-D array ('a' in this case)

    var numRows = 10,
        triangle, 
        start, 
        stop;

    // N is the no. of rows/tiers 
    // a is the 2-D array consisting of the row content

    function pascalRecursive(n, a) {

      if (n < 2) return a; 

      var prevRow = a[a.length-1];
      var curRow = [1];

      for (var i = 1; i < prevRow.length; i++) {
        curRow[i] = prevRow[i] + prevRow[i-1];
      }
      curRow.push(1);
      a.push(curRow);

      return pascalRecursive(n-1, a); // Call the function recursively
    }


    var triangle = pascalRecursive(numRows, [[1]]);

    for(var i = 0; i < triangle.length; i++)
      console.log(triangle[i]+"\n");