@@ -13,7 +13,7 @@ type equation = struct {
13
13
}
14
14
15
15
func main () {
16
- common .Setup (7 , part1 , nil )
16
+ common .Setup (7 , part1 , part2 )
17
17
}
18
18
19
19
func part1 (
@@ -26,7 +26,25 @@ func part1(
26
26
27
27
sum := 0
28
28
for _ , eq := range equations {
29
- if validateEquation (eq .Ops [0 ], eq .Test , eq .Ops [1 :]) {
29
+ if validateEquation (eq .Ops [0 ], eq .Test , eq .Ops [1 :], false ) {
30
+ sum += eq .Test
31
+ }
32
+ }
33
+
34
+ return fmt .Sprintf ("Sum of all OK tests: %d" , sum )
35
+ }
36
+
37
+ func part2 (
38
+ input string ,
39
+ ) string {
40
+ equations , err := parseEquations (input )
41
+ if err != nil {
42
+ return fmt .Sprintf ("Failed to parse input: %v" , err )
43
+ }
44
+
45
+ sum := 0
46
+ for _ , eq := range equations {
47
+ if validateEquation (eq .Ops [0 ], eq .Test , eq .Ops [1 :], true ) {
30
48
sum += eq .Test
31
49
}
32
50
}
@@ -70,14 +88,25 @@ func validateEquation(
70
88
currentValue int ,
71
89
targetValue int ,
72
90
operators []int ,
91
+ useConcatenationOperator bool ,
73
92
) bool {
74
93
if currentValue > targetValue {
75
94
return false
76
95
} else if len (operators ) == 0 {
77
96
return currentValue == targetValue
78
97
}
79
98
next := operators [0 ]
80
- mul := validateEquation (currentValue * next , targetValue , operators [1 :])
81
- add := validateEquation (currentValue + next , targetValue , operators [1 :])
82
- return mul || add
99
+ mul := validateEquation (currentValue * next , targetValue , operators [1 :], useConcatenationOperator )
100
+ add := validateEquation (currentValue + next , targetValue , operators [1 :], useConcatenationOperator )
101
+ conc := false
102
+
103
+ if useConcatenationOperator {
104
+ s := fmt .Sprintf ("%d%d" , currentValue , next )
105
+ n , err := strconv .ParseInt (s , 10 , 0 )
106
+ if err == nil {
107
+ conc = validateEquation (int (n ), targetValue , operators [1 :], true )
108
+ }
109
+ }
110
+
111
+ return mul || add || conc
83
112
}
0 commit comments