|
1 |
| -const pascal = function (counter, currentLine = [1]) { |
| 1 | +const pascal = function (counter) { |
| 2 | + const currentLine = [1]; |
2 | 3 | if (counter === 1) {
|
3 | 4 | return currentLine;
|
4 | 5 | }
|
5 | 6 |
|
6 |
| - const halfOfNextLine = currentLine.reduce( |
7 |
| - (numbers, currentNumber, index) => { |
8 |
| - const nextNumber = currentLine[index + 1]; |
9 |
| - if (currentNumber <= nextNumber) { |
10 |
| - return [...numbers, currentNumber + nextNumber]; |
11 |
| - } |
12 |
| - return numbers; |
13 |
| - }, |
14 |
| - [1], |
15 |
| - ); |
| 7 | + const previousLine = pascal(counter - 1); |
| 8 | + previousLine.forEach((number, i) => { |
| 9 | + const rightNeighbor = previousLine[i + 1] ?? 0; |
| 10 | + currentLine.push(number + rightNeighbor); |
| 11 | + }) |
16 | 12 |
|
17 |
| - // Notice that pascal triangle's lines are always palindromic in nature. |
18 |
| - // We only need the first half to obtain the information to construct the second half |
19 |
| - const joined = [...halfOfNextLine, ...halfOfNextLine.reverse()]; |
20 |
| - |
21 |
| - // If a given line of the pascal's triangle has an even amount of elements, two things are true: |
22 |
| - // - the next line will have an odd amount of elements |
23 |
| - // - the two elements in the middle will always be the same. So it's safe to remove one |
24 |
| - if (currentLine.length % 2 === 0) { |
25 |
| - joined.splice(joined.length / 2, 1); |
26 |
| - } |
27 |
| - |
28 |
| - return pascal(counter - 1, joined); |
29 |
| -}; |
| 13 | + return currentLine; |
| 14 | +} |
30 | 15 |
|
31 | 16 | // Do not edit below this line
|
32 | 17 | module.exports = pascal;
|
0 commit comments