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