Skip to content

Instantly share code, notes, and snippets.

@Overdrive141
Created July 10, 2023 09:53
Show Gist options
  • Save Overdrive141/83e8421b75f473c86f11df9e835584fa to your computer and use it in GitHub Desktop.
Save Overdrive141/83e8421b75f473c86f11df9e835584fa to your computer and use it in GitHub Desktop.
Pascal Triangle - Challenge
/**
Instructions
Compute Pascal's triangle up to a given number of rows.
In Pascal's Triangle each number is computed by adding the numbers to the right and left of the current position in the previous row.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
# ... etc
*/
export const rows = (rows) => {
// if row = 1 then 1
// row =2 => 0+1 and 0+1
// row = 3 =>
let triangle = new Array(rows);
if (rows === 0) return [];
triangle = [[1]] // base case
for (let i = 1; i < rows; i++) {
triangle[i] = new Array(i+1)
for (let j = 0; j < i+1; j++) {
const prevRowValue = computeTriangle(triangle[i-1], j, i)
triangle[i][j] = prevRowValue
}
}
return triangle
};
const computeTriangle = (prevRow, rowIndex, maxVal) => {
if (rowIndex == 0 || rowIndex >= maxVal) {
return prevRow[0] // 0th index will give us 1 always
}
else {
return prevRow[rowIndex-1] + prevRow[rowIndex]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment