Created
June 28, 2019 16:14
-
-
Save thebinarypenguin/9f0146180db54a389aa8dcf50014c877 to your computer and use it in GitHub Desktop.
Pascal's Triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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