advent_of_code_2024/day_13/solution.go

81 lines
1.6 KiB
Go
Raw Normal View History

2024-12-13 08:38:49 +00:00
package day_13
import (
"fmt"
"strings"
)
type Arcade struct {
AX, AY int
BX, BY int
PrizeX, PrizeY int
}
// task:https://adventofcode.com/2024/day/13
func SolveBasic(input string) int {
arcades := loadArcades(input)
sum := 0
for _, arcade := range arcades {
if price, solvable := solve(arcade); solvable {
sum += price
}
}
return sum
}
// task:https://adventofcode.com/2024/day/12#part2
func SolveComplex(input string) int {
arcades := fixPrizes(loadArcades(input))
sum := 0
for _, arcade := range arcades {
if price, solvable := solve(arcade); solvable {
sum += price
}
}
return sum
}
func fixPrizes(arcades []Arcade) []Arcade {
for i := range arcades {
arcades[i].PrizeX += 10000000000000
arcades[i].PrizeY += 10000000000000
}
return arcades
}
func solve(arcade Arcade) (int, bool) {
a1 := arcade.AX
b1 := arcade.BX
a2 := arcade.AY
b2 := arcade.BY
c1 := arcade.PrizeX
c2 := arcade.PrizeY
A := (c1*b2 - b1*c2) / (a1*b2 - b1*a2)
B := (c2 - a2*A) / b2
if A*arcade.AX+B*arcade.BX == arcade.PrizeX &&
A*arcade.AY+B*arcade.BY == arcade.PrizeY {
return A*3 + B, true
}
return 0, false
}
func loadArcades(input string) []Arcade {
var arcades []Arcade
for _, arcadeLine := range strings.Split(input, "\n\n") {
lines := strings.Split(arcadeLine, "\n")
arcade := Arcade{}
fmt.Sscanf(lines[0], "Button A: X+%d, Y+%d", &arcade.AX, &arcade.AY)
fmt.Sscanf(lines[1], "Button B: X+%d, Y+%d", &arcade.BX, &arcade.BY)
fmt.Sscanf(lines[2], "Prize: X=%d, Y=%d", &arcade.PrizeX, &arcade.PrizeY)
arcades = append(arcades, arcade)
}
return arcades
}