Skip to content

Commit

Permalink
Solve day 13
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulWoitaschek committed Dec 13, 2024
1 parent 3d60b3d commit 08ef2d2
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
49 changes: 49 additions & 0 deletions 2024/src/main/kotlin/aoc/year2024/Day13.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package aoc.year2024

import aoc.library.Point
import aoc.library.Puzzle

object Day13 : Puzzle<Long, Long>(day = 13) {

override fun solvePart1(input: String): Long = solve(input, prizeAddition = 0)

override fun solvePart2(input: String): Long = solve(input, prizeAddition = 10000000000000)

private fun solve(
input: String,
prizeAddition: Long,
): Long = parse(input).sumOf { it.solve(prizeAddition) }

private fun parse(input: String): List<ClawMachine> {
val buttonRegex = """Button .: X\+(\d+), Y\+(\d+)""".toRegex()
fun String.parseAsButton(): Point {
val (x, y) = buttonRegex.find(this)!!.destructured
return Point(x.toInt(), y.toInt())
}

val prizeRegex = """Prize: X=(\d+), Y=(\d+)""".toRegex()
fun String.parseAsPrize(): Point {
val (x, y) = prizeRegex.find(this)!!.destructured
return Point(x.toInt(), y.toInt())
}
return input.split("\n\n").map {
val (a, b, price) = it.lines()
ClawMachine(aButton = a.parseAsButton(), bButton = b.parseAsButton(), prize = price.parseAsPrize())
}
}

private data class ClawMachine(val aButton: Point, val bButton: Point, val prize: Point) {

fun solve(prizeAddition: Long): Long {
val px = prize.x + prizeAddition
val py = prize.y + prizeAddition
val b = (py * aButton.x - aButton.y * px) / (-aButton.y * bButton.x + aButton.x * bButton.y)
val a = (px - bButton.x * b) / aButton.x
return if (a * aButton.x + b * bButton.x == px && a * aButton.y + b * bButton.y == py) {
a * 3 + b
} else {
0
}
}
}
}
41 changes: 41 additions & 0 deletions 2024/src/test/kotlin/aoc/year2024/Day13Test.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package aoc.year2024

import aoc.library.solvePart1
import aoc.library.solvePart2
import io.kotest.matchers.longs.shouldBeExactly
import org.junit.jupiter.api.Test

class Day13Test {
@Test
fun part1TestInput() {
Day13.solvePart1(
"""
Button A: X+94, Y+34
Button B: X+22, Y+67
Prize: X=8400, Y=5400
Button A: X+26, Y+66
Button B: X+67, Y+21
Prize: X=12748, Y=12176
Button A: X+17, Y+86
Button B: X+84, Y+37
Prize: X=7870, Y=6450
Button A: X+69, Y+23
Button B: X+27, Y+71
Prize: X=18641, Y=10279
""".trimIndent(),
) shouldBeExactly 480
}

@Test
fun part1() {
Day13.solvePart1() shouldBeExactly 40069
}

@Test
fun part2() {
Day13.solvePart2() shouldBeExactly 71493195288102
}
}

0 comments on commit 08ef2d2

Please sign in to comment.