-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle08.js
100 lines (93 loc) · 2.73 KB
/
puzzle08.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const fs = require("fs");
const files = fs.readFileSync("./puzzle08-input.txt", "utf8"); //Read the input
const arr = files.replace(/\r/g, "").trim().split("\n"); //remove all carriage returns and split by single line return
const splitedArr = arr.map((x) => {
let temp = x.split("");
return temp.map(Number);
});
function partI() {
count = splitedArr.length * 2 + (splitedArr[0].length - 2) * 2;
for (let j = 1; j < splitedArr.length - 1; j++) {
for (let i = 1; i < splitedArr[0].length - 1; i++) {
//first construct four arrays on the four directions of the tree
let leftArr = [];
for (let k = 0; k < i; k++) {
leftArr.push(splitedArr[j][k]);
}
let rightArr = [];
for (let k = i + 1; k < splitedArr[0].length; k++) {
rightArr.push(splitedArr[j][k]);
}
let topArr = [];
for (let k = 0; k < j; k++) {
topArr.push(splitedArr[k][i]);
}
let bottomArr = [];
for (let k = j + 1; k < splitedArr.length; k++) {
bottomArr.push(splitedArr[k][i]);
}
//Then make sure that the tree is taller than the other trees on either of the four directions
if (
leftArr.every((x) => x < splitedArr[j][i]) ||
rightArr.every((x) => x < splitedArr[j][i]) ||
topArr.every((x) => x < splitedArr[j][i]) ||
bottomArr.every((x) => x < splitedArr[j][i])
) {
count += 1;
}
}
}
console.log(count);
}
function partII() {
let totalArea = [];
for (let j = 1; j < splitedArr.length - 1; j++) {
for (let i = 1; i < splitedArr[0].length - 1; i++) {
let countLeft = 0;
let countRight = 0;
let countTop = 0;
let countBottom = 0;
//left direction
for (k = i - 1; k >= 0; k--) {
if (splitedArr[j][i] > splitedArr[j][k]) {
countLeft += 1;
} else {
countLeft += 1;
break;
}
}
//right direction
for (k = i + 1; k < splitedArr[0].length; k++) {
if (splitedArr[j][i] > splitedArr[j][k]) {
countRight += 1;
} else {
countRight += 1;
break;
}
}
//top direction
for (k = j - 1; k >= 0; k--) {
if (splitedArr[j][i] > splitedArr[k][i]) {
countTop += 1;
} else {
countTop += 1;
break;
}
}
//bottom direction
for (k = j + 1; k < splitedArr.length; k++) {
if (splitedArr[j][i] > splitedArr[k][i]) {
countBottom += 1;
} else {
countBottom += 1;
break;
}
}
totalArea.push(countLeft * countRight * countTop * countBottom);
}
}
const highestScore = Math.max(...totalArea);
console.log(highestScore);
}
partI();
partII();