package day_07 import ( "math" "strconv" "strings" ) type Operator int const ( ADD = iota MULTIPLY = iota CONCAT = iota ) type Equation struct { Result int Variables []int } // task:https://adventofcode.com/2024/day/7 func SolveBasic(input string) int { equations := loadEquations(input) sum := 0 for _, equation := range equations { if Solvable(equation, 2) { sum += equation.Result } } return sum } func Solvable(equation Equation, operators int) bool { for i := 0; i < numberOfSolutions(equation, operators); i++ { if solvable(equation, operators, i) { return true } } return false } func numberOfSolutions(equation Equation, operators int) int { return int(math.Pow(float64(operators), float64(len(equation.Variables)-1))) } func solvable(equation Equation, operators int, options int) bool { sum := equation.Variables[0] for i := 0; i < len(equation.Variables)-1; i++ { if sum > equation.Result { return false } operator := options % operators options = options / operators switch operator { case ADD: sum += equation.Variables[i+1] case MULTIPLY: sum *= equation.Variables[i+1] case CONCAT: offset := findLarger(equation.Variables[i+1]) sum *= offset sum += equation.Variables[i+1] } } return sum == equation.Result } func findLarger(val int) int { larger := 10 for val >= larger { larger *= 10 } return larger } // task:https://adventofcode.com/2024/day/7#part2 func SolveComplex(input string) int { equations := loadEquations(input) sum := 0 for _, equation := range equations { if Solvable(equation, 3) { sum += equation.Result } } return sum } func loadEquations(input string) (equations []Equation) { lines := strings.Split(input, "\n") for _, line := range lines { equations = append(equations, loadEquation(line)) } return } func loadEquation(line string) Equation { substrings := strings.Split(line, ": ") equation := Equation{ Result: must(strconv.Atoi(substrings[0])), } for _, param := range strings.Split(substrings[1], " ") { equation.Variables = append(equation.Variables, must(strconv.Atoi(param))) } return equation } func must(val int, err error) int { if err != nil { panic(err) } return val }