Skip to content

Commit b81e9b2

Browse files
committed
Solution Day 13, part two
1 parent bb361e5 commit b81e9b2

File tree

1 file changed

+39
-6
lines changed

1 file changed

+39
-6
lines changed

src/main/kotlin/Day13.kt

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,22 @@ fun main() {
4141
}
4242
}
4343

44-
fun solveEquations(clawMachine: ClawMachine): Int {
44+
fun solveEquations(clawMachine: ClawMachine, offset: Long = 0): Long {
4545
with(clawMachine) {
4646
// formulas for a and b are deduced from the linear equations that
4747
// result directly from the problem statement for each slot machine
48-
val a = (bx * y - by * x).toDouble() / (bx * ay - by * ax)
49-
val b = (x - ax * a) / bx
48+
val a = (bx * (y + offset) - by * (x + offset)).toDouble() / (bx * ay - by * ax)
49+
val b = (x + offset - ax * a) / bx
5050
if (a.isIntegral() && b.isIntegral()) {
51-
check(a <= 100 && b <= 100) {
52-
"More than 100 button presses for $clawMachine: A: $a, B: $b"
51+
if (offset == 0L) {
52+
check(a <= 100 && b <= 100) {
53+
"More than 100 button presses for $clawMachine: A: $a, B: $b"
54+
}
5355
}
5456
check(a >= 0 && b >= 0) {
5557
"Negative button presses for $clawMachine: A: $a, B: $b"
5658
}
57-
return (a * buttonATokens + b * buttonBTokens).toInt()
59+
return (a * buttonATokens + b * buttonBTokens).toLong()
5860
}
5961
return 0
6062
}
@@ -88,6 +90,37 @@ fun main() {
8890

8991
val input = readInput(day)
9092
printAndCheck(input, ::part1, 33427)
93+
94+
95+
println("$day part 2")
96+
97+
fun part2(input: List<String>) = input
98+
.parseClawMachines()
99+
.map { solveEquations(it, 10000000000000) }
100+
.sumOf { it }
101+
102+
printAndCheck(
103+
"""
104+
Button A: X+94, Y+34
105+
Button B: X+22, Y+67
106+
Prize: X=8400, Y=5400
107+
108+
Button A: X+26, Y+66
109+
Button B: X+67, Y+21
110+
Prize: X=12748, Y=12176
111+
112+
Button A: X+17, Y+86
113+
Button B: X+84, Y+37
114+
Prize: X=7870, Y=6450
115+
116+
Button A: X+69, Y+23
117+
Button B: X+27, Y+71
118+
Prize: X=18641, Y=10279
119+
""".trimIndent().lines(),
120+
::part2, 875318608908
121+
)
122+
123+
printAndCheck(input, ::part2, 91649162972270)
91124
}
92125

93126
data class ClawMachine(val ax: Int, val ay: Int, val bx: Int, val by: Int, val x: Int, val y: Int)

0 commit comments

Comments
 (0)