remove the goroutines + waitgroups.

This commit is contained in:
onyx-and-iris 2025-01-08 06:20:43 +00:00
parent 5d6d8fdf79
commit a93e6a7a05
2 changed files with 33 additions and 69 deletions

View File

@ -2,7 +2,6 @@ package one
import ( import (
"bytes" "bytes"
"sync"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -14,34 +13,17 @@ func Solve(buf []byte) (int, error) {
return 0, err return 0, err
} }
wg := sync.WaitGroup{} var sum int
sumChan := make(chan bool)
for y := range graph.data { for y := range graph.data {
for x := range graph.data[y] { for x := range graph.data[y] {
wg.Add(1) current := newPoint(x, y)
go func() { if graph.valueAt(current) == 'X' {
defer wg.Done() for _, n := range neighbours(current) {
if checkNeighbours(n, "MAS", graph) {
current := newPoint(x, y) sum++
if graph.valueAt(current) == 'X' {
for _, n := range neighbours(current) {
sumChan <- checkNeighbours(n, "MAS", graph)
} }
} }
}() }
}
}
go func() {
wg.Wait()
close(sumChan)
}()
var sum int
for val := range sumChan {
if val {
sum++
} }
} }

View File

@ -3,7 +3,6 @@ package two
import ( import (
"bytes" "bytes"
"slices" "slices"
"sync"
) )
func Solve(buf []byte) (int, error) { func Solve(buf []byte) (int, error) {
@ -13,56 +12,39 @@ func Solve(buf []byte) (int, error) {
return 0, err return 0, err
} }
wg := sync.WaitGroup{} var sum int
sumChan := make(chan bool)
for y := range graph.data { for y := range graph.data {
for x := range graph.data[y] { for x := range graph.data[y] {
wg.Add(1) current := newPoint(x, y)
go func() { if graph.valueAt(current) == 'A' {
defer wg.Done() if func() bool {
for _, n := range neighbours(current) {
current := newPoint(x, y) if graph.isOutOfBounds(n) {
if graph.valueAt(current) == 'A' { return true
if func() bool { }
for _, n := range neighbours(current) {
if graph.isOutOfBounds(n) { if !slices.Contains([]rune{'M', 'S'}, graph.valueAt(n)) {
return true return true
}
if !slices.Contains([]rune{'M', 'S'}, graph.valueAt(n)) {
return true
}
} }
return false
}() {
return
} }
return false
ns := neighbours(current) }() {
matrix := newMatrix( continue
graph.valueAt(current),
graph.valueAt(ns[NW]),
graph.valueAt(ns[NE]),
graph.valueAt(ns[SE]),
graph.valueAt(ns[SW]),
)
sumChan <- matrix.isValid()
} }
}()
}
}
go func() { ns := neighbours(current)
wg.Wait() matrix := newMatrix(
close(sumChan) graph.valueAt(current),
}() graph.valueAt(ns[NW]),
graph.valueAt(ns[NE]),
graph.valueAt(ns[SE]),
graph.valueAt(ns[SW]),
)
var sum int if matrix.isValid() {
for val := range sumChan { sum++
if val { }
sum++ }
} }
} }