Skip to content

Instantly share code, notes, and snippets.

@cleure
Last active April 15, 2016 15:32
Show Gist options
  • Save cleure/ee0493b2c0610a0fc09693d4ea5970c4 to your computer and use it in GitHub Desktop.
Save cleure/ee0493b2c0610a0fc09693d4ea5970c4 to your computer and use it in GitHub Desktop.
Generates a row of Pascal's Triangle (zero-indexed).
'use strict';
module.exports = {
getRow: getRow
};
/**
* Generates a row of Pascal's Triangle, given row number n (zero-indexed).
* @param {Number} n
* @returns {Array<Number>}
*/
function getRow(n) {
var row = [1];
var numerator = n;
var x = 1;
var l = Math.floor((n / 2) + 1);
var i;
// Fill first half of array.
for (i = 1; i < l; i++, numerator--) {
x = Math.round((x * numerator) / i);
row.push(x);
}
// Depending on if n is even or odd will determine whether or not we need
// to read from one space back in row, or two.
x = n % 2 === 1 ? i - 1 : i - 2;
// Fill second half of array.
for (; i <= n; i++, x--) {
row.push(row[x]);
}
return row;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment