run loop logic in separate goroutines.

use bool channel + waitgroups to collect results
This commit is contained in:
onyx-and-iris 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++ {
wg.Add(1)
go func() {
defer wg.Done()
current := newPoint(j, i)
if graph.valueAt(current) == 'X' {
for _, n := range neighbours(current) {
if checkNeighbours(graph, n, "MAS") {
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)
}

View File

@ -37,7 +37,7 @@ func (m *matrix) rotate() *matrix {
return &temp
}
func (m *matrix) validate() bool {
func (m *matrix) isValid() bool {
golden := &matrix{
{'M', -1, 'M'},
{-1, 'A', -1},

View File

@ -3,6 +3,7 @@ package two
import (
"bytes"
"slices"
"sync"
)
func Solve(buf []byte) (int, error) {
@ -12,10 +13,15 @@ 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++ {
wg.Add(1)
go func() {
defer wg.Done()
current := newPoint(j, i)
if graph.valueAt(current) == 'A' {
if func() bool {
@ -30,7 +36,7 @@ func Solve(buf []byte) (int, error) {
}
return false
}() {
continue
return
}
ns := neighbours(current)
@ -42,12 +48,23 @@ func Solve(buf []byte) (int, error) {
graph.valueAt(ns[SW]),
)
if matrix.validate() {
sumChan <- matrix.isValid()
}
}()
}
}
go func() {
wg.Wait()
close(sumChan)
}()
var sum int
for val := range sumChan {
if val {
sum++
}
}
}
}
return sum, nil
}