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

Commit 3d3db09

Browse files
committed
Add solution for day 7 part 1
1 parent 1043261 commit 3d3db09

File tree

2 files changed

+76
-2
lines changed

2 files changed

+76
-2
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: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,83 @@
11
package main
22

33
import (
4+
"fmt"
45
"github.com/terminalnode/adventofcode2024/common"
6+
"strconv"
7+
"strings"
58
)
69

10+
type equation = struct {
11+
Test int
12+
Ops []int
13+
}
14+
715
func main() {
8-
common.Setup(7, nil, nil)
16+
common.Setup(7, part1, nil)
17+
}
18+
19+
func part1(
20+
input string,
21+
) string {
22+
equations, err := parseEquations(input)
23+
if err != nil {
24+
return fmt.Sprintf("Failed to parse input: %v", err)
25+
}
26+
27+
sum := 0
28+
for _, eq := range equations {
29+
if validateEquation(eq.Ops[0], eq.Test, eq.Ops[1:]) {
30+
sum += eq.Test
31+
}
32+
}
33+
34+
return fmt.Sprintf("Sum of all OK tests: %d", sum)
35+
}
36+
37+
func parseEquations(
38+
input string,
39+
) ([]equation, error) {
40+
lines := strings.Split(input, "\n")
41+
equations := make([]equation, len(lines))
42+
for i, rawEq := range lines {
43+
testSplitOps := strings.Split(rawEq, ": ")
44+
if len(testSplitOps) != 2 {
45+
return equations, fmt.Errorf("splitting %v by ': ' resulted in %d pieces (should be two)", rawEq, len(testSplitOps))
46+
}
47+
48+
test, err := strconv.ParseInt(testSplitOps[0], 10, 0)
49+
if err != nil {
50+
return equations, err
51+
}
52+
53+
splitOps := strings.Split(testSplitOps[1], " ")
54+
ops := make([]int, len(splitOps))
55+
for opI, rawOp := range splitOps {
56+
op, err := strconv.ParseInt(rawOp, 10, 0)
57+
if err != nil {
58+
return equations, err
59+
}
60+
ops[opI] = int(op)
61+
}
62+
63+
equations[i] = equation{int(test), ops}
64+
}
65+
66+
return equations, nil
67+
}
68+
69+
func validateEquation(
70+
currentValue int,
71+
targetValue int,
72+
operators []int,
73+
) bool {
74+
if currentValue > targetValue {
75+
return false
76+
} else if len(operators) == 0 {
77+
return currentValue == targetValue
78+
}
79+
next := operators[0]
80+
mul := validateEquation(currentValue*next, targetValue, operators[1:])
81+
add := validateEquation(currentValue+next, targetValue, operators[1:])
82+
return mul || add
983
}

0 commit comments

Comments
 (0)