mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 14:50:46 +00:00
68 lines
1.2 KiB
Go
68 lines
1.2 KiB
Go
|
package two
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"slices"
|
||
|
|
||
|
"github.com/onyx-and-iris/aoc2024/day-06/internal/one"
|
||
|
|
||
|
log "github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
func Solve(buf []byte) (int, error) {
|
||
|
r := bytes.NewReader(buf)
|
||
|
graph, err := parseLines(r)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
conc := len(one.Visited) - 1
|
||
|
isLoop := make(chan bool)
|
||
|
|
||
|
for loc := range one.Visited {
|
||
|
if loc.X == graph.startPoint.x && loc.Y == graph.startPoint.y {
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
g := newGraph()
|
||
|
g.startPoint = graph.startPoint
|
||
|
g.data = slices.Clone(graph.data)
|
||
|
g.data[loc.Y] = replaceAtIndex(g.data[loc.Y], 'O', loc.X)
|
||
|
|
||
|
p := g.startPoint
|
||
|
go func() {
|
||
|
visited := make(map[point]struct{})
|
||
|
|
||
|
for !(p.x == 0 && p.direction == W ||
|
||
|
p.y == 0 && p.direction == N ||
|
||
|
p.y == len(g.data)-1 && p.direction == S ||
|
||
|
p.x == len(g.data[p.y])-1 && p.direction == E) {
|
||
|
p = nextPoint(p)
|
||
|
if g.valueAt(p.x, p.y) == '#' || g.valueAt(p.x, p.y) == 'O' {
|
||
|
p.recalibrate()
|
||
|
}
|
||
|
|
||
|
_, ok := visited[p]
|
||
|
if !ok {
|
||
|
visited[p] = struct{}{}
|
||
|
} else {
|
||
|
log.Tracef("loop: \n%s\n", g.trace(visited))
|
||
|
isLoop <- true
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
isLoop <- false
|
||
|
}()
|
||
|
}
|
||
|
|
||
|
var numLoops int
|
||
|
for range conc {
|
||
|
res := <-isLoop
|
||
|
if res {
|
||
|
numLoops++
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return numLoops, nil
|
||
|
}
|