diff --git a/2024/src/main/kotlin/day13.kt b/2024/src/main/kotlin/day13.kt index 156bd7d..28c18b7 100644 --- a/2024/src/main/kotlin/day13.kt +++ b/2024/src/main/kotlin/day13.kt @@ -3,32 +3,48 @@ val regex = "Button A: X\\+(\\d+), Y\\+(\\d+)\nButton B: X\\+(\\d+), Y\\+(\\d+)\ data class Machine( val buttonA: Grid.Coordinate, val buttonB: Grid.Coordinate, - val price: Grid.Coordinate + val priceX: Long, + val priceY: Long ) { - fun solveA(b: Int) = (price.x - b * buttonB.x) / buttonA.x - fun solveB() = (price.y * buttonA.x - price.x * buttonA.y) / (buttonA.x * buttonB.y - buttonA.y * buttonB.x) + 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) - fun solve(): Pair? { + fun solve(): Pair? { val b = solveB() val a = solveA(b) - return Pair(a, b).takeIf { (a * buttonA.x + b * buttonB.x) == price.x && (a * buttonA.y + b * buttonB.y) == price.y } + return Pair( + a, + b + ).takeIf { (a * buttonA.x + b * buttonB.x) == priceX && (a * buttonA.y + b * buttonB.y) == priceY } } } fun main() { - val part1 = regex.findAll(readInputString("day13.txt")) + val machines = regex.findAll(readInputString("day13.txt")) .map { Machine( buttonA = Grid.Coordinate(it.groupValues[1].toInt(), it.groupValues[2].toInt()), buttonB = Grid.Coordinate(it.groupValues[3].toInt(), it.groupValues[4].toInt()), - price = Grid.Coordinate(it.groupValues[5].toInt(), it.groupValues[6].toInt()), + priceX = it.groupValues[5].toLong(), + priceY = it.groupValues[6].toLong() ) } - .mapNotNull { it.solve() } + .toList() + + val part1 = machines.mapNotNull { it.solve() } .sumOf { (a, b) -> 3 * a + b } println("Part 1: $part1") + 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") } \ No newline at end of file