refactor: moved out the sorted_stack to utils

This commit is contained in:
Karma Riuk 2023-08-15 18:42:58 +02:00
parent 3cccdc7eb8
commit 966387ffcd
2 changed files with 27 additions and 22 deletions

View File

@ -3,7 +3,6 @@ package solver
import ( import (
"maze-solver/maze" "maze-solver/maze"
"maze-solver/utils" "maze-solver/utils"
"slices"
"sort" "sort"
) )
@ -13,8 +12,6 @@ type DijkstraSolver struct {
stack sorted_stack stack sorted_stack
} }
type sorted_stack []*maze.Node
func (s *DijkstraSolver) Solve(m *maze.Maze) *maze.SolvedMaze { func (s *DijkstraSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("Dijkstra algorithm", 2)() defer utils.Timer("Dijkstra algorithm", 2)()
s.dist_from_start = make(map[*maze.Node]int, len(m.Nodes)) s.dist_from_start = make(map[*maze.Node]int, len(m.Nodes))
@ -64,22 +61,3 @@ func (s *DijkstraSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
Solution: solution, Solution: solution,
} }
} }
func (s *sorted_stack) insert(node *maze.Node, dists *map[*maze.Node]int) {
var dummy *maze.Node
*s = append(*s, dummy) // extend the slice
i, _ := slices.BinarySearchFunc(*s, node, func(e, t *maze.Node) int {
return (*dists)[t] - (*dists)[e]
})
copy((*s)[i+1:], (*s)[i:]) // make room
(*s)[i] = node
}
func (s *sorted_stack) pop() *maze.Node {
last_i := len(*s) - 1
ret := (*s)[last_i]
*s = (*s)[:last_i]
return ret
}

27
solver/utils.go Normal file
View File

@ -0,0 +1,27 @@
package solver
import (
"maze-solver/maze"
"slices"
)
type sorted_stack []*maze.Node
func (s *sorted_stack) insert(node *maze.Node, weights *map[*maze.Node]int) {
var dummy *maze.Node
*s = append(*s, dummy) // extend the slice
i, _ := slices.BinarySearchFunc(*s, node, func(e, t *maze.Node) int {
return (*weights)[t] - (*weights)[e]
})
copy((*s)[i+1:], (*s)[i:]) // make room
(*s)[i] = node
}
func (s *sorted_stack) pop() *maze.Node {
last_i := len(*s) - 1
ret := (*s)[last_i]
*s = (*s)[:last_i]
return ret
}