|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + _ "embed" |
| 5 | + "fmt" |
| 6 | + "strconv" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +//go:embed data.txt |
| 11 | +var fileContents string |
| 12 | + |
| 13 | +func evaluateExpression(numbers []int, ops []string) int { |
| 14 | + result := numbers[0] |
| 15 | + for i, op := range ops { |
| 16 | + if op == "+" { |
| 17 | + result += numbers[i+1] |
| 18 | + } else { |
| 19 | + result *= numbers[i+1] |
| 20 | + } |
| 21 | + } |
| 22 | + return result |
| 23 | +} |
| 24 | + |
| 25 | +func findValidEquations(desiredSum int, numbers []int) [][]string { |
| 26 | + var validEquations [][]string |
| 27 | + allowedOperations := []string{"+", "*"} |
| 28 | + |
| 29 | + // generate all possible operation combinations |
| 30 | + var generateCombinations func(int, []string) |
| 31 | + generateCombinations = func(depth int, current []string) { |
| 32 | + if depth == len(numbers)-1 { |
| 33 | + // try the current combination |
| 34 | + result := evaluateExpression(numbers, current) |
| 35 | + if result == desiredSum { |
| 36 | + validEquations = append(validEquations, append([]string{}, current...)) |
| 37 | + } |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + for _, op := range allowedOperations { |
| 42 | + generateCombinations(depth+1, append(current, op)) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + generateCombinations(0, []string{}) |
| 47 | + return validEquations |
| 48 | +} |
| 49 | + |
| 50 | +func main() { |
| 51 | + lines := strings.Split(strings.TrimSpace(fileContents), "\n") |
| 52 | + |
| 53 | + totalCalibration := 0 |
| 54 | + for _, line := range lines { |
| 55 | + parts := strings.Split(line, ": ") |
| 56 | + desiredSum, _ := strconv.Atoi(parts[0]) |
| 57 | + |
| 58 | + numberStrs := strings.Fields(parts[1]) |
| 59 | + numbers := make([]int, len(numberStrs)) |
| 60 | + for i, numStr := range numberStrs { |
| 61 | + numbers[i], _ = strconv.Atoi(numStr) |
| 62 | + } |
| 63 | + |
| 64 | + validEquations := findValidEquations(desiredSum, numbers) |
| 65 | + if len(validEquations) > 0 { |
| 66 | + totalCalibration += desiredSum |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + fmt.Println(totalCalibration) |
| 71 | +} |
0 commit comments