From 6d7aef9c1c3e3b00e488b8142708aa9c4e2378b3 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Sun, 17 Dec 2023 16:04:10 -0500 Subject: [PATCH] Add some concurrency to day 12 --- day12/main.go | 52 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/day12/main.go b/day12/main.go index f7e2eee..20bd6e9 100644 --- a/day12/main.go +++ b/day12/main.go @@ -9,6 +9,7 @@ import ( "slices" "strconv" "strings" + "sync" ) type SpringState int @@ -184,25 +185,44 @@ func main() { } func part1(records []Record) int { - total := 0 - for _, record := range records { - possibilities := record.CountPossibleStates() - total += possibilities - } - - return total + return evaluate(records) } func part2(records []Record) int { - total := 0 - for _, originalRecord := range records { - record := Record{ + repeatedRecords := make([]Record, len(records)) + for i, originalRecord := range records { + repeatedRecords[i] = Record{ states: repeatSliceWithSeparator(originalRecord.states, 4, SpringStateUnknown), sequences: repeatSlice(originalRecord.sequences, 4), } + } - possibilities := record.CountPossibleStates() - total += possibilities + return evaluate(repeatedRecords) +} + +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 @@ -356,11 +376,3 @@ func anyEqual[T comparable, S ~[]T](slice S, val T) bool { return false } - -func max(x, y int) int { - if x > y { - return x - } - - return y -}