@@ -70,24 +70,11 @@ func parse(input string) []machine {
7070}
7171
7272func 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+
111106func 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 )
0 commit comments