mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 14:50:46 +00:00
71 lines
1.2 KiB
Go
71 lines
1.2 KiB
Go
package two
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
|
|
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
|
|
res, _ := next(equation.target, equation.operands, total, joinOp)
|
|
sumChan <- res
|
|
}()
|
|
}
|
|
|
|
var sum int
|
|
for range conc {
|
|
sum += <-sumChan
|
|
}
|
|
|
|
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]
|
|
case joinOp:
|
|
opStr := fmt.Sprintf("%d%d", total, operands[0])
|
|
total = mustConv(opStr)
|
|
}
|
|
|
|
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
|
|
}
|
|
if res, ok := next(target, operands[1:], total, joinOp); ok {
|
|
return res, ok
|
|
}
|
|
|
|
return 0, false
|
|
}
|