Created
June 28, 2016 17:37
-
-
Save chirag64/ded1c4c51e2cea03808d2c4df3135c25 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Prints a Pascal Triangle of 'n' no. of lines | |
function PascalTriangle(n) { | |
var arr = []; | |
for (var i = 0; i < n; i++) { | |
// Create an array | |
arr[i] = []; | |
// Mark 1st and last element as 1 | |
arr[i][0] = 1; | |
arr[i][i] = 1; | |
// Add numbers of above elements to find value of current element | |
if (i > 0) { | |
for (var j = 1; j < i; j++) { | |
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j]; | |
} | |
} | |
// Add'em all up in a string variable after adding up the necessary spaces | |
var printStr = ''; | |
for (var j = 0; j < n - i; j++) { | |
printStr += ' '; | |
} | |
printStr += arr[i].join(' '); | |
console.log(printStr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment