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

57 lines
1009 B
Go
Raw Normal View History

2024-12-22 16:54:03 +00:00
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)
2024-12-22 16:57:19 +00:00
cache := newSequenceCache()
2024-12-22 16:54:03 +00:00
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{}{}
2024-12-22 16:57:19 +00:00
cache.upsert(sequence, lastDigit(randomiser.Secret()))
2024-12-22 16:54:03 +00:00
}
}
done <- true
}()
}
for range conc {
<-done
}
max := 0
2024-12-22 16:57:19 +00:00
for _, sum := range cache.data {
2024-12-22 16:54:03 +00:00
if sum > max {
max = sum
}
}
return max, nil
}