Skip to content

Commit 6012c0b

Browse files
committed
Day 14
1 parent 2c1a597 commit 6012c0b

File tree

2 files changed

+106
-0
lines changed

2 files changed

+106
-0
lines changed

src/main/kotlin/y24/Day14.kt

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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+
}

src/test/kotlin/y24/Day14Test.kt

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package y24
2+
3+
import common.puzzle.Input
4+
import org.junit.jupiter.api.Assertions.assertEquals
5+
import org.junit.jupiter.api.Test
6+
7+
internal class Day14Test {
8+
private val sample = Input("""
9+
p=0,4 v=3,-3
10+
p=6,3 v=-1,-3
11+
p=10,3 v=-1,2
12+
p=2,0 v=2,-1
13+
p=0,0 v=1,3
14+
p=3,0 v=-2,-2
15+
p=7,6 v=-1,-3
16+
p=3,0 v=-1,-2
17+
p=9,3 v=2,3
18+
p=7,3 v=-1,2
19+
p=2,4 v=2,-3
20+
p=9,5 v=-3,-3
21+
""".trimIndent())
22+
23+
private val day = Day14(sample, rows = 7, cols = 11)
24+
25+
@Test
26+
fun solveLevel1() {
27+
assertEquals(12, day.solveLevel1())
28+
}
29+
30+
@Test
31+
fun solveLevel2() {
32+
// Manual solution
33+
}
34+
}

0 commit comments

Comments
 (0)