Skip to content

Commit b08da1e

Browse files
committed
feat: make solution simpler (credit to @JoshDevHub)
1 parent fc4bd94 commit b08da1e

File tree

1 file changed

+9
-24
lines changed

1 file changed

+9
-24
lines changed
Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,17 @@
1-
const pascal = function (counter, currentLine = [1]) {
1+
const pascal = function (counter) {
2+
const currentLine = [1];
23
if (counter === 1) {
34
return currentLine;
45
}
56

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+
})
1612

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+
}
3015

3116
// Do not edit below this line
3217
module.exports = pascal;

0 commit comments

Comments
 (0)