Skip to content

Commit dc9c79a

Browse files
committed
Day 7 Part 2
1 parent a901437 commit dc9c79a

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

day-7/main.go

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"flag"
66
"fmt"
77
"log"
8+
"math"
89
"slices"
910
"strconv"
1011
"strings"
@@ -58,9 +59,18 @@ func part1(input string) int64 {
5859

5960
func 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

6676
func 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+
84115
func 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
106137
const (
107138
Add Operator = iota
108139
Multiply
140+
Concat
109141
)
110142

111143
func 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
}

day-7/main_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,13 @@ func Test_day7_part2(t *testing.T) {
7070
{
7171
name: "example",
7272
input: example2,
73-
want: 0,
73+
want: 11387,
7474
run: true,
7575
},
7676
{
7777
name: "actual",
7878
input: input,
79-
want: 0,
79+
want: 92148721834692,
8080
run: file.ExistsRelativeFile("input.txt"),
8181
},
8282
}

0 commit comments

Comments
 (0)