-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay06ProbablyAFireHazard.kt
69 lines (58 loc) · 2.69 KB
/
Day06ProbablyAFireHazard.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
package adventofcode.year2015
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.cartesianProduct
import adventofcode.year2015.Day06ProbablyAFireHazard.Companion.Action.TOGGLE
import adventofcode.year2015.Day06ProbablyAFireHazard.Companion.Action.TURN_OFF
import adventofcode.year2015.Day06ProbablyAFireHazard.Companion.Action.TURN_ON
import kotlin.math.max
class Day06ProbablyAFireHazard(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override val name = "Probably a Fire Hazard"
private val instructions by lazy {
input
.lines()
.map {
val (action, left, top, right, bottom) = INPUT_REGEX.find(it)!!.destructured
Instruction(Action(action), left.toInt(), top.toInt(), right.toInt(), bottom.toInt())
}
}
override fun partOne() =
instructions.fold(mutableMapOf<Pair<Int, Int>, Boolean>()) { lights, instruction ->
when (instruction.action) {
TURN_ON -> instruction.lights.forEach { light -> lights[light] = true }
TURN_OFF -> instruction.lights.forEach { light -> lights[light] = false }
TOGGLE -> instruction.lights.forEach { light -> lights[light] = !lights.getOrDefault(light, false) }
}
lights
}.count { (_, state) -> state }
override fun partTwo() =
instructions.fold(mutableMapOf<Pair<Int, Int>, Int>()) { lights, instruction ->
when (instruction.action) {
TURN_ON -> instruction.lights.forEach { light -> lights[light] = lights.getOrDefault(light, 0) + 1 }
TURN_OFF -> instruction.lights.forEach { light -> lights[light] = max(0, lights.getOrDefault(light, 0) - 1) }
TOGGLE -> instruction.lights.forEach { light -> lights[light] = lights.getOrDefault(light, 0) + 2 }
}
lights
}.values.sum()
companion object {
private val INPUT_REGEX = """(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)""".toRegex()
private data class Instruction(
val action: Action,
val left: Int,
val top: Int,
val right: Int,
val bottom: Int,
) {
val lights by lazy { listOf((left..right).toList(), (top..bottom).toList()).cartesianProduct().map { it.first() to it.last() } }
}
private enum class Action(val action: String) {
TURN_ON("turn on"),
TURN_OFF("turn off"),
TOGGLE("toggle"),
;
companion object {
operator fun invoke(action: String) = entries.associateBy(Action::action)[action]!!
}
}
}
}