|
| 1 | +package y24 |
| 2 | + |
| 3 | +import common.puzzle.solvePuzzle |
| 4 | +import common.puzzle.Input |
| 5 | +import common.puzzle.Puzzle |
| 6 | +import common.datastructures.* |
| 7 | +import common.ext.* |
| 8 | +import common.util.* |
| 9 | +import java.util.* |
| 10 | +import kotlin.math.* |
| 11 | +import kotlin.system.exitProcess |
| 12 | + |
| 13 | + |
| 14 | +fun main() = solvePuzzle(year = 2024, day = 14, dryRun = true) { Day14(it) } |
| 15 | + |
| 16 | +class Day14(val input: Input, val rows: Int = 103, val cols: Int = 101) : Puzzle { |
| 17 | + |
| 18 | + data class Robot(val p: Point, val v: Point) |
| 19 | + |
| 20 | + private fun Robot.move(n: Int): Robot { |
| 21 | + var x = p.x + v.x * n |
| 22 | + while (x < 0) x += cols |
| 23 | + var y = p.y + v.y * n |
| 24 | + while (y < 0) y += rows |
| 25 | + |
| 26 | + return Robot(Point( |
| 27 | + col = x % cols, |
| 28 | + row = y % rows, |
| 29 | + ), v) |
| 30 | + } |
| 31 | + |
| 32 | + private val robots = input.lines.map { line -> |
| 33 | + val p = Point.parse(line.substringBetween("p=", " ")) |
| 34 | + val v = Point.parse(line.substringAfter("v=")) |
| 35 | + Robot(p, v) |
| 36 | + } |
| 37 | + |
| 38 | + override fun solveLevel1(): Any { |
| 39 | + val moved = robots.map { it.move(100) } |
| 40 | + val quadrants = moved.groupBy { robot -> |
| 41 | + val qx = robot.p.x.compareTo(cols / 2).sign |
| 42 | + val qy = robot.p.y.compareTo(rows / 2).sign |
| 43 | + qx to qy |
| 44 | + }.filterKeys { (qx, qy) -> qx != 0 && qy != 0 } |
| 45 | + |
| 46 | + return quadrants.values.fold(1) { acc, robots -> acc * robots.size } |
| 47 | + } |
| 48 | + |
| 49 | + override fun solveLevel2(): Any { |
| 50 | + var robots = robots |
| 51 | + repeat(10000) { i -> |
| 52 | + val grid = Grid(rows, cols) { _, _ -> false } |
| 53 | + var numInEdge = 0 |
| 54 | + robots.forEach { r -> |
| 55 | + grid[r.p].value = true |
| 56 | + if (r.p.x !in (5..cols-5)) { |
| 57 | + numInEdge++ |
| 58 | + } |
| 59 | + } |
| 60 | + if (numInEdge < 20) { |
| 61 | + // Tree will be mostly in the center, so only print the ones that don't have many |
| 62 | + // robots on the left/right sides. |
| 63 | + println("$i:") |
| 64 | + println(grid) |
| 65 | + println() |
| 66 | + } |
| 67 | + robots = robots.map { it.move(1) } |
| 68 | + } |
| 69 | + |
| 70 | + return -1 |
| 71 | + } |
| 72 | +} |
0 commit comments