Add concurrency to day 16 part 2, just for fun :)

master
Nick Krichevsky 2023-12-18 10:58:46 -05:00
parent eee5e391ba
commit 4c7ab3776e
1 changed files with 19 additions and 5 deletions

View File

@ -7,6 +7,7 @@ import (
"os" "os"
"slices" "slices"
"strings" "strings"
"sync"
) )
type Tile rune type Tile rune
@ -161,12 +162,25 @@ func part1(grid TileGrid) int {
func part2(grid TileGrid) int { func part2(grid TileGrid) int {
startingBeams := allStartingBeams(grid) startingBeams := allStartingBeams(grid)
maxEnergy := 0 wg := sync.WaitGroup{}
answerChan := make(chan int)
for _, startingBeam := range startingBeams { for _, startingBeam := range startingBeams {
energy := simulate(grid, startingBeam) wg.Add(1)
if energy > maxEnergy { startingBeam := startingBeam
maxEnergy = energy go func() {
answerChan <- simulate(grid, startingBeam)
wg.Done()
}()
} }
go func() {
wg.Wait()
close(answerChan)
}()
maxEnergy := 0
for energy := range answerChan {
maxEnergy = max(energy, maxEnergy)
} }
return maxEnergy return maxEnergy