Skip to content

Commit 18885b3

Browse files
committed
Created 018.js + 067.js (exactly same algorithm)
1 parent a9ecb88 commit 18885b3

File tree

2 files changed

+184
-0
lines changed

2 files changed

+184
-0
lines changed

018.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//First, parse the input data
2+
3+
var inputTriangle = `75
4+
95 64
5+
17 47 82
6+
18 35 87 10
7+
20 04 82 47 65
8+
19 01 23 75 03 34
9+
88 02 77 73 07 63 67
10+
99 65 04 28 06 16 70 92
11+
41 41 26 56 83 40 80 70 33
12+
41 48 72 33 47 32 37 16 94 29
13+
53 71 44 65 25 43 91 52 97 51 14
14+
70 11 33 28 77 73 17 78 39 68 17 57
15+
91 71 52 38 17 14 91 43 58 50 27 29 48
16+
63 66 04 68 89 53 67 30 73 16 69 87 40 31
17+
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23`;
18+
19+
var triangle = inputTriangle.split("\n");
20+
21+
for (let i = 0; i < triangle.length; i++) {
22+
triangle[i] = triangle[i].split(" ").map((x) => parseInt(x));
23+
}
24+
25+
/* Algorithm: we work from the bottom up:
26+
Start at the second-to-bottom row of the triangle (row index triangle.length-2), which has n elements
27+
Add each number to the 2 numbers beneath it, and keep the higher number (add it to a temporary array)
28+
Make this array the new bottom row of the triangle (at the level of the current row) and repeat the algorithm with the row above it as the new "second-to-bottom row"
29+
*/
30+
31+
for (let i = triangle.length - 2; i >= 0; i--) {
32+
let newCurrentRow = []; //array of elements to replace the row above with
33+
34+
for (let j = 0; j < triangle[i].length; j++) {
35+
let sumWithBottomLeft = triangle[i][j] + triangle[i+1][j];
36+
let sumWithBottomRight = triangle[i][j] + triangle[i+1][j+1];
37+
38+
if (sumWithBottomLeft > sumWithBottomRight) {
39+
newCurrentRow.push(sumWithBottomLeft);
40+
} else {
41+
newCurrentRow.push(sumWithBottomRight);
42+
}
43+
}
44+
45+
triangle[i] = newCurrentRow;
46+
}
47+
48+
console.log(triangle[0][0]); //our answer will be the new value at the top of the triangle

067.js

+136
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)