|
| 1 | +package de.ronny_h.aoc.year2025.day04 |
| 2 | + |
| 3 | +import de.ronny_h.aoc.AdventOfCode |
| 4 | +import de.ronny_h.aoc.extensions.asList |
| 5 | +import de.ronny_h.aoc.extensions.grids.SimpleCharGrid |
| 6 | +import de.ronny_h.aoc.year2025.day04.PaperGrid.Companion.EMPTY |
| 7 | +import de.ronny_h.aoc.year2025.day04.PaperGrid.Companion.MARKED_PAPER |
| 8 | + |
| 9 | +fun main() = PrintingDepartment().run(1397, 8758) |
| 10 | + |
| 11 | +class PrintingDepartment : AdventOfCode<Int>(2025, 4) { |
| 12 | + override fun part1(input: List<String>): Int = PaperGrid(input).countAndMarkAccessiblePaperRolls() |
| 13 | + |
| 14 | + override fun part2(input: List<String>): Int { |
| 15 | + var paperGrid = PaperGrid(input) |
| 16 | + var total = 0 |
| 17 | + var accessiblePaperRolls = paperGrid.countAndMarkAccessiblePaperRolls() |
| 18 | + while (accessiblePaperRolls > 0) { |
| 19 | + total += accessiblePaperRolls |
| 20 | + paperGrid = paperGrid.copyReplacing(MARKED_PAPER, EMPTY) |
| 21 | + accessiblePaperRolls = paperGrid.countAndMarkAccessiblePaperRolls() |
| 22 | + } |
| 23 | + return total |
| 24 | + } |
| 25 | + |
| 26 | +} |
| 27 | + |
| 28 | +class PaperGrid(input: List<String>) : SimpleCharGrid(input, EMPTY) { |
| 29 | + |
| 30 | + companion object { |
| 31 | + private const val PAPER = '@' |
| 32 | + const val MARKED_PAPER = 'x' |
| 33 | + const val EMPTY = '.' |
| 34 | + } |
| 35 | + |
| 36 | + fun countAndMarkAccessiblePaperRolls() = |
| 37 | + forEachCoordinates { position, element -> |
| 38 | + if (element.isAPaperRoll() && position.neighboursIncludingDiagonals() |
| 39 | + .count { this[it].isAPaperRoll() } < 4 |
| 40 | + ) { |
| 41 | + this[position] = MARKED_PAPER |
| 42 | + 1 |
| 43 | + } else { |
| 44 | + 0 |
| 45 | + } |
| 46 | + }.sum() |
| 47 | + |
| 48 | + fun copyReplacing(oldElement: Char, newElement: Char): PaperGrid { |
| 49 | + val newGridString = toString().replace(oldElement, newElement) |
| 50 | + return PaperGrid(newGridString.asList()) |
| 51 | + } |
| 52 | + |
| 53 | + private fun Char.isAPaperRoll(): Boolean = this == PAPER || this == MARKED_PAPER |
| 54 | +} |
0 commit comments