Skip to content

Instantly share code, notes, and snippets.

@janetlee
Last active October 27, 2017 06:53
Show Gist options
  • Save janetlee/3a62efc9cc37f99676448a9ff4bd8a7d to your computer and use it in GitHub Desktop.
Save janetlee/3a62efc9cc37f99676448a9ff4bd8a7d to your computer and use it in GitHub Desktop.
Pascal's Triangle
function triangle(num) {
var result = [[1], [1,1]];
for (var j = 0; j < num; j++) {
// console.log('previousArr', result[result.length-1]);
var previousArr = result[result.length-1];
var tempArr = [];
// for each element of previous array
for (var i = 0; i < previousArr.length ; i++) {
// is this the 0 element?
if (i === 0) {
// Yes: push to temporary array
tempArr.push(previousArr[i]);
// result.push(i);
} else if (i > 0 && i === previousArr.length-1) {
// No: Add element and previous array element-1
var sum = previousArr[i] + previousArr[i-1];
// push to temporary array
tempArr.push(sum);
tempArr.push(previousArr[previousArr.length-1]);
result.push(tempArr);
// No: Is this the last element of previous array?
} else {
var middleSum = previousArr[i] + previousArr[i-1];
tempArr.push(middleSum);
}
}
// is the result array length equal to the input number?
if (result.length === num) {
// Yes: Stop and return the result
return result;
}
// No: continue looping
}
return result;
}
console.log(triangle(7));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment