mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 14:50:46 +00:00
63 lines
1.0 KiB
Go
63 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 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
|
||
|
}
|