make use of graph factory function.

move isLoop logic into guard clause.
This commit is contained in:
onyx-and-iris 2024-12-06 22:23:01 +00:00
parent 8bf3f603d5
commit 08706ecc11
4 changed files with 9 additions and 11 deletions

View File

@ -7,8 +7,8 @@ import (
) )
type graph struct { type graph struct {
data []string
startPoint point startPoint point
data []string
} }
func newGraph() *graph { func newGraph() *graph {

View File

@ -7,12 +7,12 @@ import (
) )
type graph struct { type graph struct {
data []string
startPoint point startPoint point
data []string
} }
func newGraph() *graph { func newGraph(startPoint point, data []string) *graph {
return &graph{} return &graph{startPoint: startPoint, data: data}
} }
func (g *graph) String() string { func (g *graph) String() string {

View File

@ -24,9 +24,7 @@ func Solve(buf []byte) (int, error) {
continue continue
} }
g := newGraph() g := newGraph(graph.startPoint, slices.Clone(graph.data))
g.startPoint = graph.startPoint
g.data = slices.Clone(graph.data)
g.data[loc.Y] = replaceAtIndex(g.data[loc.Y], 'O', loc.X) g.data[loc.Y] = replaceAtIndex(g.data[loc.Y], 'O', loc.X)
p := g.startPoint p := g.startPoint
@ -43,13 +41,13 @@ func Solve(buf []byte) (int, error) {
} }
_, ok := visited[p] _, ok := visited[p]
if !ok { if ok {
visited[p] = struct{}{}
} else {
log.Tracef("loop: \n%s\n", g.trace(visited)) log.Tracef("loop: \n%s\n", g.trace(visited))
isLoop <- true isLoop <- true
return return
} }
visited[p] = struct{}{}
} }
isLoop <- false isLoop <- false
}() }()

View File

@ -7,7 +7,7 @@ import (
) )
func parseLines(r io.Reader) (*graph, error) { func parseLines(r io.Reader) (*graph, error) {
graph := newGraph() graph := &graph{}
count := 0 count := 0
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)