Skip to content

Instantly share code, notes, and snippets.

@thebinarypenguin
Created June 28, 2019 16:14
Show Gist options
  • Save thebinarypenguin/9f0146180db54a389aa8dcf50014c877 to your computer and use it in GitHub Desktop.
Save thebinarypenguin/9f0146180db54a389aa8dcf50014c877 to your computer and use it in GitHub Desktop.
Pascal's Triangle
'use strict';
/**
* Display a Pascal Triangle
*
* @param {number} numRows Number of rows to display
*/
const displayPascalTriangle = function (numRows = 0) {
if (numRows < 0) {
console.log('Error: numRows must not be negative');
}
const triangle = [];
// Rows
for (let n = 0; n < numRows; n++) {
triangle[n] = [];
// Cols
for (let k = 0; k <= n; k++) {
if (k === 0 || k === n) {
// First and last numbers in row are always 1
triangle[n][k] = 1;
}
else {
// Inside numbers are the sum of the 2 numbers directly "above" them
triangle[n][k] = triangle[n-1][k-1] + triangle[n-1][k];
}
}
// Display row (left justified)
console.log(triangle[n].join(' '));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment