Add some concurrency to day 12

master
Nick Krichevsky 2023-12-17 16:04:10 -05:00
parent 623e2eaf68
commit 6d7aef9c1c
1 changed files with 32 additions and 20 deletions

View File

@ -9,6 +9,7 @@ import (
"slices" "slices"
"strconv" "strconv"
"strings" "strings"
"sync"
) )
type SpringState int type SpringState int
@ -184,25 +185,44 @@ func main() {
} }
func part1(records []Record) int { func part1(records []Record) int {
total := 0 return evaluate(records)
for _, record := range records {
possibilities := record.CountPossibleStates()
total += possibilities
}
return total
} }
func part2(records []Record) int { func part2(records []Record) int {
total := 0 repeatedRecords := make([]Record, len(records))
for _, originalRecord := range records { for i, originalRecord := range records {
record := Record{ repeatedRecords[i] = Record{
states: repeatSliceWithSeparator(originalRecord.states, 4, SpringStateUnknown), states: repeatSliceWithSeparator(originalRecord.states, 4, SpringStateUnknown),
sequences: repeatSlice(originalRecord.sequences, 4), sequences: repeatSlice(originalRecord.sequences, 4),
} }
}
possibilities := record.CountPossibleStates() return evaluate(repeatedRecords)
total += possibilities }
func evaluate(records []Record) int {
total := 0
answerChan := make(chan int)
wg := sync.WaitGroup{}
// Concurrently, just for fun :)
for _, record := range records {
wg.Add(1)
r := record
go func() {
possibilities := r.CountPossibleStates()
answerChan <- possibilities
wg.Done()
}()
}
go func() {
wg.Wait()
close(answerChan)
}()
for answer := range answerChan {
total += answer
} }
return total return total
@ -356,11 +376,3 @@ func anyEqual[T comparable, S ~[]T](slice S, val T) bool {
return false return false
} }
func max(x, y int) int {
if x > y {
return x
}
return y
}