2024-12-14 14:10:04 +01:00
|
|
|
val regex = "Button A: X\\+(\\d+), Y\\+(\\d+)\nButton B: X\\+(\\d+), Y\\+(\\d+)\nPrize: X=(\\d+), Y=(\\d+)".toRegex()
|
|
|
|
|
|
|
|
data class Machine(
|
|
|
|
val buttonA: Grid.Coordinate,
|
|
|
|
val buttonB: Grid.Coordinate,
|
2024-12-14 14:14:30 +01:00
|
|
|
val priceX: Long,
|
|
|
|
val priceY: Long
|
2024-12-14 14:10:04 +01:00
|
|
|
) {
|
|
|
|
|
2024-12-14 14:14:30 +01:00
|
|
|
fun solveA(b: Long) = (priceX - b * buttonB.x) / buttonA.x
|
|
|
|
fun solveB() = (priceY * buttonA.x - priceX * buttonA.y) / (buttonA.x * buttonB.y - buttonA.y * buttonB.x)
|
2024-12-14 14:10:04 +01:00
|
|
|
|
2024-12-14 14:14:30 +01:00
|
|
|
fun solve(): Pair<Long, Long>? {
|
2024-12-14 14:10:04 +01:00
|
|
|
val b = solveB()
|
|
|
|
val a = solveA(b)
|
|
|
|
|
2024-12-14 14:14:30 +01:00
|
|
|
return Pair(
|
|
|
|
a,
|
|
|
|
b
|
|
|
|
).takeIf { (a * buttonA.x + b * buttonB.x) == priceX && (a * buttonA.y + b * buttonB.y) == priceY }
|
2024-12-14 14:10:04 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fun main() {
|
2024-12-14 14:14:30 +01:00
|
|
|
val machines = regex.findAll(readInputString("day13.txt"))
|
2024-12-14 14:10:04 +01:00
|
|
|
.map {
|
|
|
|
Machine(
|
|
|
|
buttonA = Grid.Coordinate(it.groupValues[1].toInt(), it.groupValues[2].toInt()),
|
|
|
|
buttonB = Grid.Coordinate(it.groupValues[3].toInt(), it.groupValues[4].toInt()),
|
2024-12-14 14:14:30 +01:00
|
|
|
priceX = it.groupValues[5].toLong(),
|
|
|
|
priceY = it.groupValues[6].toLong()
|
2024-12-14 14:10:04 +01:00
|
|
|
)
|
|
|
|
}
|
2024-12-14 14:14:30 +01:00
|
|
|
.toList()
|
|
|
|
|
|
|
|
val part1 = machines.mapNotNull { it.solve() }
|
2024-12-14 14:10:04 +01:00
|
|
|
.sumOf { (a, b) -> 3 * a + b }
|
|
|
|
|
|
|
|
println("Part 1: $part1")
|
|
|
|
|
2024-12-14 14:14:30 +01:00
|
|
|
val part2 = machines.map {
|
|
|
|
it.copy(
|
|
|
|
priceX = it.priceX + 10000000000000,
|
|
|
|
priceY = it.priceY + 10000000000000
|
|
|
|
)
|
|
|
|
}.mapNotNull { it.solve() }
|
|
|
|
.sumOf { (a, b) -> 3 * a + b }
|
|
|
|
|
|
|
|
println("Part 2: $part2")
|
2024-12-14 14:10:04 +01:00
|
|
|
}
|