Skip to content

Commit

Permalink
Day 7 Part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
shaunburdick committed Dec 11, 2024
1 parent a901437 commit dc9c79a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
40 changes: 38 additions & 2 deletions day-7/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"flag"
"fmt"
"log"
"math"
"slices"
"strconv"
"strings"
Expand Down Expand Up @@ -58,9 +59,18 @@ func part1(input string) int64 {

func part2(input string) int64 {
parsed := parseInput(input)
_ = parsed
var total int64
total = 0

for _, calibration := range parsed {
testValue, numbers := ParseCalibration(calibration)
iter := IterateOperatorsWithConcat(numbers[0], numbers[1:])
if slices.Contains(iter, testValue) {
total += testValue
}
}

return 0
return total
}

func IterateOperators(carry int64, numbers []int64) (results []int64) {
Expand All @@ -81,6 +91,27 @@ func IterateOperators(carry int64, numbers []int64) (results []int64) {
return results
}

func IterateOperatorsWithConcat(carry int64, numbers []int64) (results []int64) {
addResult := ApplyOperator(Add, carry, numbers[0])
mulResult := ApplyOperator(Multiply, carry, numbers[0])
conResult := ApplyOperator(Concat, carry, numbers[0])

// base case
if len(numbers) == 1 {
results = append(results, addResult, mulResult, conResult)
} else {
nextAdd := IterateOperatorsWithConcat(addResult, numbers[1:])
nextMul := IterateOperatorsWithConcat(mulResult, numbers[1:])
nextCon := IterateOperatorsWithConcat(conResult, numbers[1:])

results = append(results, nextAdd...)
results = append(results, nextMul...)
results = append(results, nextCon...)
}

return results
}

func ParseCalibration(c string) (testValue int64, numbers []int64) {
calSplit := strings.Split(c, ":")
tv, tvErr := strconv.Atoi(calSplit[0])
Expand All @@ -106,6 +137,7 @@ type Operator int
const (
Add Operator = iota
Multiply
Concat
)

func ApplyOperator(op Operator, a int64, b int64) int64 {
Expand All @@ -114,6 +146,10 @@ func ApplyOperator(op Operator, a int64, b int64) int64 {
return a + b
case Multiply:
return a * b
case Concat:
digitsB := int(math.Log10(float64(b))) + 1
shiftedA := (a * int64(math.Pow10(digitsB)))
return shiftedA + b
default:
panic("Unknown Operator")
}
Expand Down
4 changes: 2 additions & 2 deletions day-7/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,13 @@ func Test_day7_part2(t *testing.T) {
{
name: "example",
input: example2,
want: 0,
want: 11387,
run: true,
},
{
name: "actual",
input: input,
want: 0,
want: 92148721834692,
run: file.ExistsRelativeFile("input.txt"),
},
}
Expand Down

0 comments on commit dc9c79a

Please sign in to comment.