add day-07 + benchmarks

This commit is contained in:
2024-12-07 23:39:28 +00:00
parent 1c60c034e3
commit d42df0cd84
20 changed files with 425 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
goos: linux
goarch: amd64
pkg: github.com/onyx-and-iris/aoc2024/day-07/internal/two
cpu: Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
BenchmarkSolve-12 1000000000 0.2539 ns/op
ok github.com/onyx-and-iris/aoc2024/day-07/internal/two 3.822s

View File

@@ -0,0 +1,10 @@
package two
type equation struct {
target int
operands []int
}
func newEquation(res int, operands []int) equation {
return equation{res, operands}
}

View File

@@ -0,0 +1,7 @@
package two
const (
sumOp = "+"
prodOp = "*"
joinOp = "||"
)

View File

@@ -0,0 +1,70 @@
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
if res, ok := next(equation.target, equation.operands, total, joinOp); 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]
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
}

View File

@@ -0,0 +1,15 @@
package two
import (
_ "embed"
"os"
"testing"
)
//go:embed testdata/input.txt
var data []byte
func BenchmarkSolve(b *testing.B) {
os.Stdout, _ = os.Open(os.DevNull)
Solve(data)
}

View File

@@ -0,0 +1,37 @@
package two
import (
"bufio"
"io"
"strconv"
"strings"
)
func mustConv(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return n
}
func parseLines(r io.Reader) ([]equation, error) {
equations := []equation{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
parts := strings.Split(scanner.Text(), ":")
res := mustConv(parts[0])
var operands []int
for _, s := range strings.Fields(parts[1]) {
operands = append(operands, mustConv(string(s)))
}
equations = append(equations, newEquation(res, operands))
}
if err := scanner.Err(); err != nil {
return nil, err
}
return equations, nil
}