run loop logic in separate goroutines.

use bool channel + waitgroups to collect results
This commit is contained in:
2025-01-07 17:22:03 +00:00
parent feb0ae4617
commit c70d4a74cf
3 changed files with 71 additions and 37 deletions

View File

@@ -2,6 +2,7 @@ package one
import (
"bytes"
"sync"
log "github.com/sirupsen/logrus"
)
@@ -13,37 +14,53 @@ func Solve(buf []byte) (int, error) {
return 0, err
}
var sum int
wg := sync.WaitGroup{}
sumChan := make(chan bool)
for i := 0; i < len(graph.data); i++ {
for j := 0; j < len(graph.data[i]); j++ {
current := newPoint(j, i)
if graph.valueAt(current) == 'X' {
for _, n := range neighbours(current) {
if checkNeighbours(graph, n, "MAS") {
sum++
wg.Add(1)
go func() {
defer wg.Done()
current := newPoint(j, i)
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++
}
}
return sum, nil
}
func checkNeighbours(graph *graph, n point, word string) bool {
func checkNeighbours(n point, word string, g *graph) bool {
if len(word) == 0 {
log.Debug("we found a full XMAS")
return true
}
if graph.isOutOfBounds(n) {
if g.isOutOfBounds(n) {
return false
}
if graph.valueAt(n) != rune(word[0]) {
if g.valueAt(n) != rune(word[0]) {
return false
}
return checkNeighbours(graph, neighbours(n)[n.direction], word[1:])
return checkNeighbours(neighbours(n)[n.direction], word[1:], g)
}