aoc2024/day-04/internal/two/solve.go

71 lines
1.1 KiB
Go

package two
import (
"bytes"
"slices"
"sync"
)
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 y := range graph.data {
for x := range graph.data[y] {
wg.Add(1)
go func() {
defer wg.Done()
current := newPoint(x, y)
if graph.valueAt(current) == 'A' {
if func() bool {
for _, n := range neighbours(current) {
if graph.isOutOfBounds(n) {
return true
}
if !slices.Contains([]rune{'M', 'S'}, graph.valueAt(n)) {
return true
}
}
return false
}() {
return
}
ns := neighbours(current)
matrix := newMatrix(
graph.valueAt(current),
graph.valueAt(ns[NW]),
graph.valueAt(ns[NE]),
graph.valueAt(ns[SE]),
graph.valueAt(ns[SW]),
)
sumChan <- matrix.isValid()
}
}()
}
}
go func() {
wg.Wait()
close(sumChan)
}()
var sum int
for val := range sumChan {
if val {
sum++
}
}
return sum, nil
}