Day 13 part 1
This commit is contained in:
parent
b8411307bb
commit
37cd83d3ae
3 changed files with 1328 additions and 0 deletions
34
2024/src/main/kotlin/day13.kt
Normal file
34
2024/src/main/kotlin/day13.kt
Normal file
|
@ -0,0 +1,34 @@
|
|||
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,
|
||||
val price: Grid.Coordinate
|
||||
) {
|
||||
|
||||
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 solve(): Pair<Int, Int>? {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
fun main() {
|
||||
val part1 = 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()),
|
||||
)
|
||||
}
|
||||
.mapNotNull { it.solve() }
|
||||
.sumOf { (a, b) -> 3 * a + b }
|
||||
|
||||
println("Part 1: $part1")
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue