Skip to content

Commit 41e69e0

Browse files
committed
task: Day 13: Claw Contraption
1 parent 4075a1e commit 41e69e0

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎day_13/main.go‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package main
2+
3+
import (
4+
_ "embed"
5+
"fmt"
6+
"github.com/Norbiros/AoC2024/utils"
7+
"gonum.org/v1/gonum/mat"
8+
"math"
9+
"strings"
10+
)
11+
12+
//go:embed input.txt
13+
var input string
14+
15+
// I know this solution isn't bulletproof
16+
// It won't work, for example, for buttons [1, 1] = 2 [5, 5] = 10
17+
// But it worked for my dataset :3
18+
func main() {
19+
fmt.Println("Solving \"Day 13: Claw Contraption\"...")
20+
fmt.Println("Part 1 result", solve(input, 0))
21+
fmt.Println("Part 2 result", solve(input, 10000000000000))
22+
}
23+
24+
func parseCoordinates(line, prefix string) []int {
25+
line = strings.ReplaceAll(line, prefix, "")
26+
line = strings.ReplaceAll(line, ", Y", " ")
27+
line = strings.ReplaceAll(line, "=", "")
28+
values := strings.Fields(line)
29+
return []int{utils.ToInt(values[0]), utils.ToInt(values[1])}
30+
}
31+
32+
func solve(input string, difference int) int {
33+
var resultValue int
34+
for _, line := range strings.Split(input, "\n\n") {
35+
lines := strings.Split(line, "\n")
36+
buttonA := parseCoordinates(lines[0], "Button A: X")
37+
buttonB := parseCoordinates(lines[1], "Button B: X")
38+
39+
prize := parseCoordinates(lines[2], "Prize: X")
40+
prize[0] += difference
41+
prize[1] += difference
42+
43+
matrix := mat.NewDense(2, 2, []float64{
44+
float64(buttonA[0]), float64(buttonB[0]),
45+
float64(buttonA[1]), float64(buttonB[1]),
46+
})
47+
result := mat.NewDense(2, 1, []float64{
48+
float64(prize[0]),
49+
float64(prize[1]),
50+
})
51+
52+
var solution mat.Dense
53+
err := solution.Solve(matrix, result)
54+
if err != nil {
55+
fmt.Println("Error solving equations:", err)
56+
continue
57+
}
58+
59+
a, b := solution.At(0, 0), solution.At(1, 0)
60+
61+
const epsilon = 1e-4
62+
if math.Abs(a-math.Round(a)) < epsilon && math.Abs(b-math.Round(b)) < epsilon {
63+
resultValue += int(math.Round(a)*3 + math.Round(b))
64+
}
65+
66+
}
67+
return resultValue
68+
}

0 commit comments

Comments
 (0)