Skip to content

Commit 8362b5c

Browse files
committed
bug: Fix day13 solution
1 parent b9739da commit 8362b5c

File tree

2 files changed

+29
-14
lines changed

2 files changed

+29
-14
lines changed

src/day13/day13.go

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -70,24 +70,11 @@ func parse(input string) []machine {
7070
}
7171

7272
func solveMachine(m machine) (bool, uint) {
73-
if outOfRange(m) {
74-
return false, 0
75-
}
76-
7773
a, b := cramersRule([2][2]int{{m.buttonA.x, m.buttonB.x}, {m.buttonA.y, m.buttonB.y}}, [2][1]int{{m.prize.x}, {m.prize.y}})
7874
if a == 0 && b == 0 {
7975
return manualSolution(m)
8076
}
81-
positiveOnly := a > 0 && b >= 0 || a >= 0 && b > 0
82-
return positiveOnly, uint(a*BUTTON_A_COST + b*BUTTON_B_COST)
83-
}
84-
85-
func outOfRange(m machine) bool {
86-
maxX := max(m.buttonA.x, m.buttonB.x)
87-
cantReachX := maxX != 0 && m.prize.x/maxX > BUTTON_PUSH_LIMIT+1
88-
maxY := max(m.buttonA.y, m.buttonB.y)
89-
cantReachY := maxY != 0 && m.prize.y/maxY > BUTTON_PUSH_LIMIT+1
90-
return cantReachX || cantReachY
77+
return validSolution(m, a, b), uint(a*BUTTON_A_COST + b*BUTTON_B_COST)
9178
}
9279

9380
// @see{https://en.wikipedia.org/wiki/Cramer's_rule#Explicit_formulas_for_small_systems}
@@ -108,6 +95,14 @@ func determinate(input [2][2]int) int {
10895
return input[0][0]*input[1][1] - input[0][1]*input[1][0]
10996
}
11097

98+
func validSolution(m machine, a, b int) bool {
99+
positiveOnly := (a > 0 && b >= 0) || (a >= 0 && b > 0)
100+
withinLimits := a <= 100 && b <= 100
101+
validAnswer := (a*m.buttonA.x+b*m.buttonB.x == m.prize.x) && (a*m.buttonA.y+b*m.buttonB.y == m.prize.y)
102+
103+
return positiveOnly && withinLimits && validAnswer
104+
}
105+
111106
func manualSolution(m machine) (bool, uint) {
112107
a, costa := linearSolution(m.buttonA, m.prize, BUTTON_A_COST)
113108
b, costb := linearSolution(m.buttonB, m.prize, BUTTON_B_COST)

src/day13/day13_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,23 @@ Prize: X=0, Y=9`
9595
t.Errorf("Calculated solution was not expected")
9696
}
9797
}
98+
99+
func TestStretchesTowardsMax(t *testing.T) {
100+
input := `Button A: X+98, Y+61
101+
Button B: X+23, Y+50
102+
Prize: X=10248, Y=7378`
103+
prizes, tokens := Solve(input)
104+
if prizes != 1 || tokens != 322 {
105+
t.Errorf("Calculated solution was not expected")
106+
}
107+
}
108+
109+
func TestDetNotWholeNumber(t *testing.T) {
110+
input := `Button A: X+31, Y+54
111+
Button B: X+30, Y+14
112+
Prize: X=1879, Y=1440`
113+
prizes, tokens := Solve(input)
114+
if prizes != 0 || tokens != 0 {
115+
t.Errorf("Calculated solution was not expected")
116+
}
117+
}

0 commit comments

Comments
 (0)