Skip to content
This repository was archived by the owner on Dec 28, 2024. It is now read-only.

Commit 259cde9

Browse files
committed
Add solution for day 7 part 2
1 parent 3d3db09 commit 259cde9

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ automatically rebuilt and redeployed ever time the `common` module or their own
5151
| 04 | ⭐ ⭐ | 17 | |
5252
| 05 | ⭐ ⭐ | 18 | |
5353
| 06 | ⭐ ⭐ | 19 | |
54-
| 07 | | 20 | |
54+
| 07 | | 20 | |
5555
| 08 | | 21 | |
5656
| 09 | | 22 | |
5757
| 10 | | 23 | |

solutions/day07/main.go

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ type equation = struct {
1313
}
1414

1515
func main() {
16-
common.Setup(7, part1, nil)
16+
common.Setup(7, part1, part2)
1717
}
1818

1919
func part1(
@@ -26,7 +26,25 @@ func part1(
2626

2727
sum := 0
2828
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) {
3048
sum += eq.Test
3149
}
3250
}
@@ -70,14 +88,25 @@ func validateEquation(
7088
currentValue int,
7189
targetValue int,
7290
operators []int,
91+
useConcatenationOperator bool,
7392
) bool {
7493
if currentValue > targetValue {
7594
return false
7695
} else if len(operators) == 0 {
7796
return currentValue == targetValue
7897
}
7998
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
83112
}

0 commit comments

Comments
 (0)