aoc2024/day-22/internal/two/solve.go

57 lines
1009 B
Go

package two
import (
"bytes"
"math"
"github.com/onyx-and-iris/aoc2024/day-22/internal/randomiser"
)
const numIterations = 2000
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
secrets, err := parseLines(r)
if err != nil {
return 0, err
}
conc := len(secrets)
done := make(chan bool)
cache := newSequenceCache()
for _, secret := range secrets {
go func() {
seen := make(map[sequence]struct{})
sequence := sequence{math.MaxInt, math.MaxInt, math.MaxInt, math.MaxInt}
randomiser := randomiser.New(secret)
for range numIterations {
prev := lastDigit(randomiser.Secret())
randomiser.Randomise()
sequence.shift(prev - lastDigit(randomiser.Secret()))
_, ok := seen[sequence]
if !ok {
seen[sequence] = struct{}{}
cache.upsert(sequence, lastDigit(randomiser.Secret()))
}
}
done <- true
}()
}
for range conc {
<-done
}
max := 0
for _, sum := range cache.data {
if sum > max {
max = sum
}
}
return max, nil
}