aoc2024/day-07/internal/one/solve.go
2024-12-07 23:47:20 +00:00

67 lines
1.0 KiB
Go

package one
import (
"bytes"
log "github.com/sirupsen/logrus"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
equations, err := parseLines(r)
if err != nil {
return 0, err
}
conc := len(equations)
sumChan := make(chan int)
for _, equation := range equations {
go func() {
var total int
if res, ok := next(equation.target, equation.operands, total, sumOp); ok {
sumChan <- res
return
}
sumChan <- 0
}()
}
var sum int
for range conc {
res := <-sumChan
sum += res
}
return sum, nil
}
func next(target int, operands []int, total int, operator string) (int, bool) {
if total > target {
return 0, false
}
if len(operands) == 0 {
if total == target {
log.Debug(total)
return total, true
}
return 0, false
}
switch operator {
case sumOp:
total += operands[0]
case prodOp:
total *= operands[0]
}
if res, ok := next(target, operands[1:], total, sumOp); ok {
return res, ok
}
if res, ok := next(target, operands[1:], total, prodOp); ok {
return res, ok
}
return 0, false
}