|
| 1 | +package de.ronny_h.aoc.year2018.day03 |
| 2 | + |
| 3 | +import de.ronny_h.aoc.AdventOfCode |
| 4 | +import de.ronny_h.aoc.extensions.grids.Coordinates |
| 5 | + |
| 6 | +fun main() = NoMatterHowYouSliceIt().run(107820, 661) |
| 7 | + |
| 8 | +class NoMatterHowYouSliceIt : AdventOfCode<Int>(2018, 3) { |
| 9 | + override fun part1(input: List<String>): Int = ClaimedAreas(input).numberOfOverlaps() |
| 10 | + override fun part2(input: List<String>): Int = ClaimedAreas(input).findTheOneThatDoesntOverlap().id |
| 11 | +} |
| 12 | + |
| 13 | +data class Claim(val id: Int, val x: Int, val y: Int, val width: Int, val height: Int) |
| 14 | + |
| 15 | +private val claimPattern = """#(\d+) @ (\d+),(\d+): (\d+)x(\d+)""".toPattern() |
| 16 | + |
| 17 | +fun List<String>.parseClaims() = map { |
| 18 | + val matcher = claimPattern.matcher(it) |
| 19 | + matcher.find() |
| 20 | + check(matcher.groupCount() == 5) |
| 21 | + Claim( |
| 22 | + id = matcher.group(1).toInt(), |
| 23 | + x = matcher.group(2).toInt(), |
| 24 | + y = matcher.group(3).toInt(), |
| 25 | + width = matcher.group(4).toInt(), |
| 26 | + height = matcher.group(5).toInt(), |
| 27 | + ) |
| 28 | +} |
| 29 | + |
| 30 | +class ClaimedAreas(input: List<String>) { |
| 31 | + private val claims = input.parseClaims() |
| 32 | + private val claimedAreas = mutableMapOf<Coordinates, Int>().withDefault { 0 } |
| 33 | + |
| 34 | + init { |
| 35 | + claims.forEach { |
| 36 | + for (x in it.x..<it.x + it.width) { |
| 37 | + for (y in it.y..<it.y + it.height) { |
| 38 | + claimedAreas[Coordinates(y, x)] = claimedAreas.getValue(Coordinates(y, x)) + 1 |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + fun numberOfOverlaps() = claimedAreas.values.count { it > 1 } |
| 45 | + |
| 46 | + fun findTheOneThatDoesntOverlap(): Claim = claims |
| 47 | + .filter { |
| 48 | + for (x in it.x..<it.x + it.width) { |
| 49 | + for (y in it.y..<it.y + it.height) { |
| 50 | + if (claimedAreas.getValue(Coordinates(y, x)) > 1) return@filter false |
| 51 | + } |
| 52 | + } |
| 53 | + true |
| 54 | + } |
| 55 | + .single() |
| 56 | +} |
0 commit comments