I wrote a function to generate a complicated version of the pascal triangle. The generated triangle should look like that:
┌─────────┬───┬───┬────┬────┬────┬────┬────┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │
├─────────┼───┼───┼────┼────┼────┼────┼────┼───┼───┤
│ 0 │ 1 │ │ │ │ │ │ │ │ │
│ 1 │ 1 │ 1 │ 1 │ │ │ │ │ │ │
│ 2 │ 1 │ 2 │ 3 │ 2 │ 1 │ │ │ │ │
│ 3 │ 1 │ 3 │ 6 │ 7 │ 6 │ 3 │ 1 │ │ │
│ 4 │ 1 │ 4 │ 10 │ 16 │ 19 │ 13 │ 10 │ 4 │ 1 │
└─────────┴───┴───┴────┴────┴────┴────┴────┴───┴───┘
My implementation is like that
function createTriangle (n) {
// initialize the holding matrix
let matrix = [];
// iterate over the matrix rows, and for each row construct a new array of row number + 1
for (let row = 0; row < n; row++) {
matrix[row] = new Array(row+1);
// iterate over each row and check conditions
for (let col = 0; col <= 2*row; col++) {
if ((col === 0 && row >= 0) || (col === 2 * row)) {
matrix[row][col] = 1;
// first case
} else if(col === row && col === 1){
matrix[row][col] = 1;
// second case ;
} else if(row > col && matrix[row][col-1]=== 1 ) {
matrix[row][col] =
1 + matrix[row-1][col];
// third case
} else if(row > col && matrix[row][col-1]!== 1 ) {
matrix[row][col] =
matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// fourth case
} else if((row === col && (matrix[row][col-1] !== 1))) {
matrix[row][col] =
matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// fifth case
// if the col number is even, add only the previous 2 elements in the previous row
} else if(row < col && col % 2 === 0){
matrix[row][col] = matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// sixth case
// if the col number is odd add the previous 3 elements in the previous row
} else if(row < col && col % 2 === 1){
matrix[row][col] = matrix[row-1][col-2] + matrix[row-1][col-1];
}
}
}
return matrix;
}
console.table(createTriangle(5))
I feel that my code is a bit confusing. In addition, there is a bug on matrix[4, 5] it should be 16,but it is 13?? Could anyone advise if there is a more refactored elegant solution? Appreciate your time and help.
Edit The algorithm should generate a matrix that have number of columns twice number of rows. The elements before the element at matrix[row][col] where col = row should be the same but reversed in a desc. order. for example, matrix[4,4] => [1,4,10,16,19,16,10,4,1]. element at matrix[4,4] 19 should be equal to 6+7+6