|
1 | 1 | package main
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
4 | 5 | "github.com/terminalnode/adventofcode2024/common"
|
| 6 | + "strconv" |
| 7 | + "strings" |
5 | 8 | )
|
6 | 9 |
|
| 10 | +type equation = struct { |
| 11 | + Test int |
| 12 | + Ops []int |
| 13 | +} |
| 14 | + |
7 | 15 | 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 |
9 | 83 | }
|
0 commit comments