55 "flag"
66 "fmt"
77 "log"
8+ "math"
89 "slices"
910 "strconv"
1011 "strings"
@@ -58,9 +59,18 @@ func part1(input string) int64 {
5859
5960func part2 (input string ) int64 {
6061 parsed := parseInput (input )
61- _ = parsed
62+ var total int64
63+ total = 0
64+
65+ for _ , calibration := range parsed {
66+ testValue , numbers := ParseCalibration (calibration )
67+ iter := IterateOperatorsWithConcat (numbers [0 ], numbers [1 :])
68+ if slices .Contains (iter , testValue ) {
69+ total += testValue
70+ }
71+ }
6272
63- return 0
73+ return total
6474}
6575
6676func IterateOperators (carry int64 , numbers []int64 ) (results []int64 ) {
@@ -81,6 +91,27 @@ func IterateOperators(carry int64, numbers []int64) (results []int64) {
8191 return results
8292}
8393
94+ func IterateOperatorsWithConcat (carry int64 , numbers []int64 ) (results []int64 ) {
95+ addResult := ApplyOperator (Add , carry , numbers [0 ])
96+ mulResult := ApplyOperator (Multiply , carry , numbers [0 ])
97+ conResult := ApplyOperator (Concat , carry , numbers [0 ])
98+
99+ // base case
100+ if len (numbers ) == 1 {
101+ results = append (results , addResult , mulResult , conResult )
102+ } else {
103+ nextAdd := IterateOperatorsWithConcat (addResult , numbers [1 :])
104+ nextMul := IterateOperatorsWithConcat (mulResult , numbers [1 :])
105+ nextCon := IterateOperatorsWithConcat (conResult , numbers [1 :])
106+
107+ results = append (results , nextAdd ... )
108+ results = append (results , nextMul ... )
109+ results = append (results , nextCon ... )
110+ }
111+
112+ return results
113+ }
114+
84115func ParseCalibration (c string ) (testValue int64 , numbers []int64 ) {
85116 calSplit := strings .Split (c , ":" )
86117 tv , tvErr := strconv .Atoi (calSplit [0 ])
@@ -106,6 +137,7 @@ type Operator int
106137const (
107138 Add Operator = iota
108139 Multiply
140+ Concat
109141)
110142
111143func ApplyOperator (op Operator , a int64 , b int64 ) int64 {
@@ -114,6 +146,10 @@ func ApplyOperator(op Operator, a int64, b int64) int64 {
114146 return a + b
115147 case Multiply :
116148 return a * b
149+ case Concat :
150+ digitsB := int (math .Log10 (float64 (b ))) + 1
151+ shiftedA := (a * int64 (math .Pow10 (digitsB )))
152+ return shiftedA + b
117153 default :
118154 panic ("Unknown Operator" )
119155 }
0 commit comments