-
Notifications
You must be signed in to change notification settings - Fork 4
/
Day23.kt
76 lines (68 loc) · 2.88 KB
/
Day23.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
package com.github.ephemient.aoc2022
@Day
class Day23(lines: List<String>) {
private val states = directions.scan(
buildSet { lines.forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') add(x to y) } } }
) { state, directions ->
val proposals = state.groupingBy { position ->
if (position.neighbors().none { it in state }) {
position
} else {
directions.firstNotNullOfOrNull { direction ->
if (position.neighbors(direction).none { it in state }) position.move(direction) else null
} ?: position
}
}.aggregateTo(mutableMapOf()) { _, _: IntPair?, value, first -> if (first) value else null }
proposals.entries.removeAll { (key, value) -> value == null || key == value }
buildSet(state.size) {
addAll(state)
removeAll(proposals.values.toSet())
addAll(proposals.keys)
}
}
@Day.Part
fun part1(): Int {
val state = states.elementAt(10)
val minX = state.minOf { it.first }
val maxX = state.maxOf { it.first }
val minY = state.minOf { it.second }
val maxY = state.maxOf { it.second }
return (maxX - minX + 1) * (maxY - minY + 1) - state.size
}
@Day.Part
fun part2(): Int = states.zipWithNext().indexOfFirst { (prev, cur) -> prev == cur } + 1
private enum class Direction {
N, S, W, E
}
companion object {
private val directions = sequence {
val directions = ArrayDeque(Direction.values().asList())
while (true) {
yield(directions.toList())
directions.add(directions.removeFirst())
}
}
private fun IntPair.neighbors(): Array<IntPair> = arrayOf(
first + 1 to second,
first + 1 to second + 1,
first to second + 1,
first - 1 to second + 1,
first - 1 to second,
first - 1 to second - 1,
first to second - 1,
first + 1 to second - 1,
)
private fun IntPair.neighbors(direction: Direction): Array<IntPair> = when (direction) {
Direction.N -> arrayOf(first - 1 to second - 1, first to second - 1, first + 1 to second - 1)
Direction.S -> arrayOf(first - 1 to second + 1, first to second + 1, first + 1 to second + 1)
Direction.W -> arrayOf(first - 1 to second - 1, first - 1 to second, first - 1 to second + 1)
Direction.E -> arrayOf(first + 1 to second - 1, first + 1 to second, first + 1 to second + 1)
}
private fun IntPair.move(direction: Direction) = when (direction) {
Direction.N -> first to second - 1
Direction.S -> first to second + 1
Direction.W -> first - 1 to second
Direction.E -> first + 1 to second
}
}
}