@@ -70,24 +70,11 @@ func parse(input string) []machine {
70
70
}
71
71
72
72
func solveMachine (m machine ) (bool , uint ) {
73
- if outOfRange (m ) {
74
- return false , 0
75
- }
76
-
77
73
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 }})
78
74
if a == 0 && b == 0 {
79
75
return manualSolution (m )
80
76
}
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 )
91
78
}
92
79
93
80
// @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 {
108
95
return input [0 ][0 ]* input [1 ][1 ] - input [0 ][1 ]* input [1 ][0 ]
109
96
}
110
97
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
+
111
106
func manualSolution (m machine ) (bool , uint ) {
112
107
a , costa := linearSolution (m .buttonA , m .prize , BUTTON_A_COST )
113
108
b , costb := linearSolution (m .buttonB , m .prize , BUTTON_B_COST )
0 commit comments