-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03_pt2.js
94 lines (89 loc) · 2.11 KB
/
day03_pt2.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
const directions = ["E", "N", "W", "S"]
function getNeighbors(coord) {
let [x, y] = coord
//find all the neighbors of a coordinate and store it
let neighbors = []
for (let i = x - 1; i <= x + 1; i++) {
for (let j = y - 1; j <= y + 1; j++) {
if (!(x == i && y == j)) {
neighbors.push([i, j])
}
}
}
return neighbors
}
function sumNeighbors(coord, matrix) {
let [x, y] = coord
//find all the neighbors of a coordinate and store it
let neighbors = getNeighbors(coord)
//iterate over each neighbor, check if it's populated and if it is, sum it.
let sum = 0
neighbors.forEach((neighborCoord) => {
let [a, b] = neighborCoord
matrix.forEach((matrixObj) => {
let [c, d] = matrixObj.position
if (a === c && b === d) {
sum += matrixObj.value
}
})
})
return sum
}
function determineNextCoord(coord, matrix, currentDirection) {
let [x, y] = coord
let neighbors = getNeighbors(coord)
let populatedNeighbors = 0
neighbors.forEach((neighbor) => {
let [a, b] = neighbor
for (const matrixObj of matrix) {
let [c, d] = matrixObj.position
if (a === c && b === d) {
populatedNeighbors++
}
}
})
if (populatedNeighbors <= 2 && populatedNeighbors > 0) {
currentIndex = directions.indexOf(currentDirection)
currentDirection = directions[(currentIndex + 1) % 4]
}
switch (currentDirection) {
case "N":
return [x, y + 1, "N"]
break
case "W":
return [x - 1, y, "W"]
break
case "S":
return [x, y - 1, "S"]
break
case "E":
return [x + 1, y, "E"]
break
default:
console.log(`current direction unknown: ${currentDirection}`)
}
}
const matrix = [
{
position: [0, 0],
value: 1,
direction: "E",
},
]
let nextValue = 1
let i = 0
while (nextValue < 400000) {
let [x, y, nextDirection] = determineNextCoord(
matrix[i].position,
matrix,
matrix[i].direction
)
nextValue = sumNeighbors([x, y], matrix)
matrix.push({
position: [x, y],
value: nextValue,
direction: nextDirection,
})
console.log(matrix[i])
i++
}