Skip to content

Instantly share code, notes, and snippets.

@adekbadek
Last active February 28, 2016 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adekbadek/5ff39b8c68599ae60939 to your computer and use it in GitHub Desktop.
Save adekbadek/5ff39b8c68599ae60939 to your computer and use it in GitHub Desktop.
// Print n lines of Pascal's triangle
function new_line(line){
// function takes the last line and based on that creates the next one
var new_line_array = [],
next_int;
// iterate over the line, which is an array of integers
for(var i=0; i<line.length; i++ ){
var a = parseInt(line[i]);
var b = parseInt(line[i-1]);
if(isNaN(b)){
b = 0;
}
// next integer is the sum of integers with indexes i and i-1
next_int = a + b;
new_line_array.push(next_int);
}
new_line_array.push(1);
// return the new line
return new_line_array;
}
// here, use the above function recursively, as many times as many lines you want to print
function pascal(n){
// first line is just '1'
var last_line = [1];
// print the initial line, which is line 0
console.log(last_line.join(' '));
// for as many times as the current iteration no.
for(var i=1; i<=n; i++){
// create next line
var line = new_line(last_line) ;
// print the line
console.log(line.join(' '));
// assign the new line to last_line
last_line = line;
}
}
// print 15 lines of a Pascal's triangle
pascal(15);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment