advent_of_code_2024/day_07/solution.go

81 lines
1.5 KiB
Go
Raw Normal View History

2024-12-08 13:21:14 +00:00
package day_07
import (
"strconv"
"strings"
)
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) {
sum += equation.Result
}
}
return sum
}
func Solvable(equation Equation) bool {
for i := 0; i < 1<<(len(equation.Variables)-1); i++ {
if solvable(equation, i) {
return true
}
}
return false
}
func solvable(equation Equation, options int) bool {
sum := equation.Variables[0]
for i := 0; i < len(equation.Variables)-1; i++ {
if sum > equation.Result {
return false
}
if options&(1<<i) != 0 {
sum *= equation.Variables[i+1]
} else {
sum += equation.Variables[i+1]
}
}
return sum == equation.Result
}
// task:https://adventofcode.com/2024/day/7#part2
func SolveComplex(input string) int {
return 0
}
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
}