|
| 1 | +fun main() { |
| 2 | + val day = "Day14" |
| 3 | + |
| 4 | + val robotPattern = """p=(\d+),(\d+) v=(-?\d+),(-?\d+)""".toRegex() |
| 5 | + |
| 6 | + println("$day part 1") |
| 7 | + |
| 8 | + fun List<String>.parseRobots() = map { |
| 9 | + val (px, py, vx, vy) = robotPattern.find(it)!!.destructured |
| 10 | + Robot(px.toInt(), py.toInt(), vx.toInt(), vy.toInt()) |
| 11 | + } |
| 12 | + |
| 13 | + fun List<Robot>.move(width: Int, height: Int, seconds: Int) = map { |
| 14 | + it.copy( |
| 15 | + px = (it.px + seconds * it.vx).mod(width), |
| 16 | + py = (it.py + seconds * it.vy).mod(height), |
| 17 | + ) |
| 18 | + } |
| 19 | + |
| 20 | + fun List<Robot>.countQuadrants(width: Int, height: Int) = fold(QuadrantCounts(0, 0, 0, 0)) { counts, it -> |
| 21 | + if (it.px in 0..<width / 2 && it.py in 0..<height / 2) { |
| 22 | + counts.q1++ |
| 23 | + } |
| 24 | + if (it.px in width / 2 + 1..width && it.py in 0..<height / 2) { |
| 25 | + counts.q2++ |
| 26 | + } |
| 27 | + if (it.px in 0..<width / 2 && it.py in height / 2 + 1..height) { |
| 28 | + counts.q3++ |
| 29 | + } |
| 30 | + if (it.px in width / 2 + 1..width && it.py in height / 2 + 1..height) { |
| 31 | + counts.q4++ |
| 32 | + } |
| 33 | + counts |
| 34 | + } |
| 35 | + |
| 36 | + fun part1Small(input: List<String>): Int { |
| 37 | + val width = 11 |
| 38 | + val height = 7 |
| 39 | + val (q1, q2, q3, q4) = input.parseRobots() |
| 40 | + .move(width, height, 100) |
| 41 | + .countQuadrants(width, height) |
| 42 | + return q1 * q2 * q3 * q4 |
| 43 | + } |
| 44 | + |
| 45 | + fun part1(input: List<String>): Int { |
| 46 | + val width = 101 |
| 47 | + val height = 103 |
| 48 | + val (q1, q2, q3, q4) = input.parseRobots() |
| 49 | + .move(width, height, 100) |
| 50 | + .countQuadrants(width, height) |
| 51 | + return q1 * q2 * q3 * q4 |
| 52 | + } |
| 53 | + |
| 54 | + printAndCheck( |
| 55 | + """ |
| 56 | + p=0,4 v=3,-3 |
| 57 | + p=6,3 v=-1,-3 |
| 58 | + p=10,3 v=-1,2 |
| 59 | + p=2,0 v=2,-1 |
| 60 | + p=0,0 v=1,3 |
| 61 | + p=3,0 v=-2,-2 |
| 62 | + p=7,6 v=-1,-3 |
| 63 | + p=3,0 v=-1,-2 |
| 64 | + p=9,3 v=2,3 |
| 65 | + p=7,3 v=-1,2 |
| 66 | + p=2,4 v=2,-3 |
| 67 | + p=9,5 v=-3,-3 |
| 68 | + """.trimIndent().lines(), |
| 69 | + ::part1Small, 12 |
| 70 | + ) |
| 71 | + |
| 72 | + val input = readInput(day) |
| 73 | + printAndCheck(input, ::part1, 218433348) |
| 74 | +} |
| 75 | + |
| 76 | +data class Robot(val px: Int, val py: Int, val vx: Int, val vy: Int) |
| 77 | + |
| 78 | +data class QuadrantCounts(var q1: Int, var q2: Int, var q3: Int, var q4: Int) |
0 commit comments