|
| 1 | +package de.ronny_h.aoc.year2015.day06 |
| 2 | + |
| 3 | +import de.ronny_h.aoc.AdventOfCode |
| 4 | +import de.ronny_h.aoc.extensions.Coordinates |
| 5 | +import de.ronny_h.aoc.year2015.day06.Action.OFF |
| 6 | +import de.ronny_h.aoc.year2015.day06.Action.ON |
| 7 | +import de.ronny_h.aoc.year2015.day06.Action.TOGGLE |
| 8 | + |
| 9 | +fun main() = FireHazard().run(400410, 15343601) |
| 10 | + |
| 11 | +class FireHazard : AdventOfCode<Int>(2015, 6) { |
| 12 | + |
| 13 | + private val onOfGrid = List(1000) { |
| 14 | + MutableList(1000) { false } |
| 15 | + } |
| 16 | + |
| 17 | + private fun switch(switchLight: SwitchLight) = with(switchLight) { |
| 18 | + for (row in from.row..to.row) { |
| 19 | + for (col in from.col..to.col) { |
| 20 | + when(action) { |
| 21 | + ON -> onOfGrid[row][col] = true |
| 22 | + OFF -> onOfGrid[row][col] = false |
| 23 | + TOGGLE -> onOfGrid[row][col] = !onOfGrid[row][col] |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + override fun part1(input: List<String>): Int { |
| 30 | + input.map(::parse).forEach(::switch) |
| 31 | + return onOfGrid.sumOf { row -> row.count { it } } |
| 32 | + } |
| 33 | + |
| 34 | + fun parse(line: String): SwitchLight { |
| 35 | + val action = when { |
| 36 | + line.startsWith(ON.text) -> ON |
| 37 | + line.startsWith(OFF.text) -> OFF |
| 38 | + line.startsWith(TOGGLE.text) -> TOGGLE |
| 39 | + else -> error("invalid start of line: $line") |
| 40 | + } |
| 41 | + val (from, to) = line.substring(action.text.length).split(" through ") |
| 42 | + val (fromRow, fromCol) = from.split(',').map(String::toInt) |
| 43 | + val (toRow, toCol) = to.split(',').map(String::toInt) |
| 44 | + return SwitchLight(action, Coordinates(fromRow, fromCol), Coordinates(toRow, toCol)) |
| 45 | + } |
| 46 | + |
| 47 | + private val dimmingGrid = List(1000) { |
| 48 | + MutableList(1000) { 0 } |
| 49 | + } |
| 50 | + |
| 51 | + private fun dim(switchLight: SwitchLight) = with(switchLight) { |
| 52 | + for (row in from.row..to.row) { |
| 53 | + for (col in from.col..to.col) { |
| 54 | + when(action) { |
| 55 | + ON -> dimmingGrid[row][col]++ |
| 56 | + OFF -> if (dimmingGrid[row][col] > 0) dimmingGrid[row][col]-- |
| 57 | + TOGGLE -> dimmingGrid[row][col] = dimmingGrid[row][col] + 2 |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + override fun part2(input: List<String>): Int { |
| 64 | + input.map(::parse).forEach(::dim) |
| 65 | + return dimmingGrid.sumOf { row -> row.sumOf { it } } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +data class SwitchLight(val action: Action, val from: Coordinates, val to: Coordinates) |
| 70 | + |
| 71 | +enum class Action(val text: String) { |
| 72 | + ON("turn on "), OFF("turn off "), TOGGLE("toggle ") |
| 73 | +} |
0 commit comments