Skip to content

Commit fbc74a6

Browse files
committed
feat(pascal): create solution
1 parent 13c66f4 commit fbc74a6

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed
Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,33 @@
1-
const pascal = function() {
2-
// Replace this comment with the solution code
1+
const pascal = function (counter, currentLine = [1]) {
2+
if (counter === 1) return currentLine;
3+
4+
const halfOfNextLine = currentLine.reduce(
5+
(accumulator, currentElement, index, originalArray) => {
6+
const nextElement = originalArray[index + 1]
7+
if (currentElement <= nextElement) {
8+
return [...accumulator, currentElement + nextElement];
9+
}
10+
return accumulator;
11+
},
12+
[1],
13+
);
14+
15+
// Notice that pascal triangle's lines are always palindromic in nature.
16+
// We only need the first half to obtain the information to
17+
// Construct the second half
18+
const joined = [...halfOfNextLine, ...halfOfNextLine.reverse()];
19+
20+
// If a given line of the pascal's triangle has an even amount of elements, two things are true:
21+
// - the next line will have an odd amount of elements
22+
// - the two elements in the middle will always be the same. So we are save to remove one
23+
if (currentLine.length % 2 === 0) {
24+
joined.splice(joined.length / 2, 1);
25+
}
26+
27+
return pascal(counter - 1, joined);
328
};
4-
29+
30+
pascal(5)
31+
532
// Do not edit below this line
633
module.exports = pascal;

0 commit comments

Comments
 (0)