-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day18.kt
80 lines (73 loc) · 2.89 KB
/
Day18.kt
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
package aoc2018.day18
import util.Coord
fun playGameOfLumberyards(inputMap: Map<Coord, Char>, minutes: Int): Int {
var fieldMap = inputMap.toMutableMap()
repeat(minutes) {
fieldMap = computeNextSnapshot(fieldMap)
}
return fieldMap.values.count { it == '|' } * fieldMap.values.count { it == '#' }
}
fun playLongGameOfLumberyards(inputMap: Map<Coord, Char>, minutes: Long): Int {
val firstSnapShot = gridToString(inputMap)
val snapshotList = mutableListOf(firstSnapShot)
var newSnapshot = inputMap.toMutableMap()
var runCount = 1
val cycleCount: Int
while (true) {
newSnapshot = computeNextSnapshot(newSnapshot)
val newSnapshotString = gridToString(newSnapshot)
if (snapshotList.contains(newSnapshotString)) {
cycleCount = runCount - snapshotList.indexOf(newSnapshotString)
break
}
snapshotList.add(gridToString(newSnapshot))
runCount++
}
// The cycle begins after the # of total runs minus the first time an existing grid was met.
// To compute what the grid looks like after 1 bil minutes, we can subtract the value obtained above from the minutes,
// then add the remainder of the division diff / cycle
val runsBeforeCycleBegins = runCount - cycleCount
return playGameOfLumberyards(
inputMap,
(runsBeforeCycleBegins + (minutes - runsBeforeCycleBegins) % cycleCount).toInt()
)
}
private fun computeNextSnapshot(fieldMap: MutableMap<Coord, Char>): MutableMap<Coord, Char> {
val mapCopy = fieldMap.toMutableMap()
for (acre in fieldMap.entries) {
val neighbors = getNeighborAcres(acre.key, fieldMap)
when (acre.value) {
'.' -> mapCopy[acre.key] = if (neighbors.treeCount >= 3) '|' else '.'
'|' -> mapCopy[acre.key] = if (neighbors.lumberYardCount >= 3) '#' else '|'
'#' -> mapCopy[acre.key] = if (neighbors.lumberYardCount >= 1 && neighbors.treeCount >= 1) '#' else '.'
}
}
return mapCopy
}
fun gridToString(map: Map<Coord, Char>): String {
var string = ""
map.values.forEach { acre -> string += acre }
return string
}
fun getNeighborAcres(acre: Coord, map: Map<Coord, Char>): NeighborAcres {
val deltaCoords = listOf(
Coord(-1, -1), Coord(0, -1), Coord(1, -1),
Coord(-1, 0), Coord(1, 0),
Coord(-1, 1), Coord(0, 1), Coord(1, 1)
)
var openCount = 0
var treeCount = 0
var lumberYardCount = 0
for (delta in deltaCoords) {
val neighbor = Coord(acre.x + delta.x, acre.y + delta.y)
if (map[neighbor] != null) {
when (map[neighbor]) {
'.' -> openCount++
'|' -> treeCount++
'#' -> lumberYardCount++
}
}
}
return NeighborAcres(openCount, treeCount, lumberYardCount)
}
data class NeighborAcres(val openCount: Int, val treeCount: Int, val lumberYardCount: Int)