diff --git a/day5/day5.go b/day5/day5.go index 5f9762a..6c42478 100644 --- a/day5/day5.go +++ b/day5/day5.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "strings" + "sync" "gitea.paas.celticinfo.fr/oabrivard/aoc2023/utils" ) @@ -38,7 +39,7 @@ func buildMapList(start int, lines []string) ([]*SrcToDest, int) { func srcToDest(src int64, stdList []*SrcToDest) int64 { for _, std := range stdList { - if std.src <= src && src <= std.src+std.rng { + if std.src <= src && src <= std.src+std.rng-1 { return src + std.dst - std.src } } @@ -87,25 +88,43 @@ func FindRangedClosestLocation(lines []string) int64 { tempToHumid, i := buildMapList(i, lines) humidToLoc, _ := buildMapList(i, lines) - result := int64(math.MaxInt64) + var wg sync.WaitGroup + ch := make(chan int64, len(seeds)/2) - count := 0 for i := 0; i < len(seeds); i += 2 { - count++ - for seed := seeds[i]; seed < seeds[i]+seeds[i+1]; seed++ { - d1 := srcToDest(seed, seedToSoil) - d2 := srcToDest(d1, soilToFert) - d3 := srcToDest(d2, fertToWater) - d4 := srcToDest(d3, waterToLight) - d5 := srcToDest(d4, lightToTemp) - d6 := srcToDest(d5, tempToHumid) - d7 := srcToDest(d6, humidToLoc) - - if d7 < result { - result = d7 + wg.Add(1) + + go func(s int64, r int64) { + defer wg.Done() + result := int64(math.MaxInt64) + + for seed := s; seed < s+r; seed++ { + d1 := srcToDest(seed, seedToSoil) + d2 := srcToDest(d1, soilToFert) + d3 := srcToDest(d2, fertToWater) + d4 := srcToDest(d3, waterToLight) + d5 := srcToDest(d4, lightToTemp) + d6 := srcToDest(d5, tempToHumid) + d7 := srcToDest(d6, humidToLoc) + + if d7 < result { + result = d7 + } } + + fmt.Println("seed roots done:", result) + ch <- result + }(seeds[i], seeds[i+1]) + } + wg.Wait() + close(ch) + + result := int64(math.MaxInt64) + for i := range ch { + if i < result { + result = i } - fmt.Println("seed roots done:", count) } + return result } diff --git a/day5/day5_test.go b/day5/day5_test.go index 235e49f..76dd3c1 100644 --- a/day5/day5_test.go +++ b/day5/day5_test.go @@ -109,7 +109,7 @@ func TestRangedFindClosestLocationWithInput(t *testing.T) { lines := utils.ReadLines("input.txt") result := FindRangedClosestLocation(lines) - if result != 1181555926 { - t.Fatalf("expected 37806487, got %d", result) + if result != 37806486 { + t.Fatalf("expected 37806486, got %d", result) } }