day5: parallelized

This commit is contained in:
efim 2023-12-05 11:37:55 +00:00
parent 7dbc09d3f8
commit 7e6a543790
1 changed files with 28 additions and 5 deletions

View File

@ -8,6 +8,7 @@ import (
"sort"
"strconv"
"strings"
"sync"
)
type Almanach struct {
@ -113,14 +114,36 @@ func Run() int {
seedRanges = append(seedRanges, []int{start, start+seedRangeLen})
}
rangeMins := make(chan int, len(seedRanges))
var wg sync.WaitGroup
mergedSeedRanges := merge(seedRanges)
for _, seedRange := range mergedSeedRanges {
log.Printf("starting new range %+v. current min is %n", seedRange, result)
for i := seedRange[0]; i <= seedRange[1]; i++ {
location := almanach.locationForSeed(i)
if location < result {
result = location
wg.Add(1)
go func(seedRange []int) {
log.Printf("starting new range %+v. current min is %d", seedRange, result)
rangeMin := math.MaxInt
for i := seedRange[0]; i <= seedRange[1]; i++ {
location := almanach.locationForSeed(i)
if location < rangeMin {
rangeMins<- location
rangeMin = location
}
}
wg.Done()
return
}(seedRange)
}
go func() {
wg.Wait()
close(rangeMins)
}()
for rangeMin := range rangeMins {
log.Printf("processing range min : %d. cur result is %d", rangeMin, result)
if rangeMin <= result {
result = rangeMin
}
}