aoc2024/day-04/internal/one/solve.go
onyx-and-iris c70d4a74cf run loop logic in separate goroutines.
use bool channel + waitgroups to collect results
2025-01-07 17:22:03 +00:00

67 lines
1023 B
Go

package one
import (
"bytes"
"sync"
log "github.com/sirupsen/logrus"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
graph, err := readLines(r)
if err != nil {
return 0, err
}
wg := sync.WaitGroup{}
sumChan := make(chan bool)
for i := 0; i < len(graph.data); i++ {
for j := 0; j < len(graph.data[i]); j++ {
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(n point, word string, g *graph) bool {
if len(word) == 0 {
log.Debug("we found a full XMAS")
return true
}
if g.isOutOfBounds(n) {
return false
}
if g.valueAt(n) != rune(word[0]) {
return false
}
return checkNeighbours(neighbours(n)[n.direction], word[1:], g)
}