23 Commits

Author SHA1 Message Date
e40c41ddfb feat: implemented a* algorithm 2023-08-15 18:43:18 +02:00
966387ffcd refactor: moved out the sorted_stack to utils 2023-08-15 18:42:58 +02:00
3cccdc7eb8 feat: implememented dijkstra algorithm 2023-08-15 17:22:10 +02:00
ab902e64b9 Refactor: wasVisited -> visited 2023-08-15 15:42:53 +02:00
120bd29d86 refactor: removed map for visited and added field to node 2023-08-15 15:41:24 +02:00
27cb446573 Implemented bfs 2023-08-14 20:00:59 +02:00
7cb4fa99bc Pulled out the wasVisited function from DFS to genral solver 2023-08-14 20:00:41 +02:00
e53dac17d5 Fixed the default cell size to avoid having to put it every time 2023-08-14 19:59:57 +02:00
4f79d6f1ed Removed useless print statements 2023-08-14 15:09:24 +02:00
346cfe9705 Finally written some good tests for the image writer 2023-08-14 15:08:27 +02:00
94af003adc Added some assets 2023-08-14 15:08:13 +02:00
aec655610a Added files to gitignore 2023-08-14 15:07:10 +02:00
2423645f3a Removed log statement 2023-08-14 14:27:07 +02:00
6e0a1032d1 Figured out that the implementation of turn left
was actually dfs lol
2023-08-13 21:31:47 +02:00
69afaed1bf fixed lil mistake eheh 2023-08-11 14:34:12 +02:00
908e8c14fb Commented out image writer tests cuz i gotta think
of a good way to do them :)
2023-08-11 14:31:51 +02:00
954d44085c Fixed workflows 2023-08-11 14:29:35 +02:00
8a6543cc1e Updated the github workflows 2023-08-11 14:27:24 +02:00
485efeebaf Does this one work? 2023-08-11 14:18:52 +02:00
f803dc7771 Fixed github workflow (hopefully) 2023-08-11 14:10:35 +02:00
46c42cb67d Refactored main.go to make the entry point clearer 2023-08-11 14:09:31 +02:00
32f7720069 Added github workflow for auto-generating
pre-resleases
2023-08-11 14:05:55 +02:00
3c7c181911 Fixed failing tests 2023-08-11 13:48:39 +02:00
21 changed files with 454 additions and 68 deletions

View File

@ -0,0 +1,33 @@
---
name: "pre-release"
on:
push:
branches:
- "main"
jobs:
pre-release:
name: "Pre Release"
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: "1.21"
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
- uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "latest"
prerelease: true
title: "Development Build"

31
.github/workflows/tagged-release.yml vendored Normal file
View File

@ -0,0 +1,31 @@
---
name: "tagged-release"
on:
push:
tags:
- "v*"
jobs:
tagged-release:
name: "Tagged Release"
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: "1.21"
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
- uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false

2
.gitignore vendored
View File

@ -20,3 +20,5 @@
# Go workspace file
go.work
/Session.vim
/maze.png
/maze_sol.png

BIN
assets/real.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

BIN
assets/solved/normal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

BIN
assets/solved/normal2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
assets/solved/real.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 316 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 424 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 B

BIN
assets/solved/trivial.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 B

View File

@ -1,17 +1,24 @@
package writer
import (
"bytes"
"image/color"
"io"
"maze-solver/maze"
"os"
"testing"
"github.com/mazznoer/colorgrad"
)
const (
OUT_DIR = "./out"
EXPECTED_DIR = "../../assets/solved"
)
func TestImageWriter(t *testing.T) {
pathGradient, err := colorgrad.NewGradient().Colors(color.White).Build()
if err != nil {
panic(err)
if _, err := os.Stat(OUT_DIR); os.IsNotExist(err) {
os.Mkdir(OUT_DIR, 0700)
}
tests := []struct {
@ -24,33 +31,33 @@ func TestImageWriter(t *testing.T) {
}{
{
"Trivial",
"../../out/trivial_sol.png",
"trivial.png",
trivial(),
40, 40,
20, 20,
color.White, color.Black,
colorgrad.Warm(),
},
{
"Bigger",
"../../out/bigger_sol.png",
"Trivial Bigger",
"trivial-bigger.png",
bigger(),
40, 40,
20, 20,
color.White, color.Black,
colorgrad.Warm(),
},
{
"Bigger Staggered",
"../../out/bigger_staggered_sol.png",
"Trivial Bigger Staggered",
"trivial-bigger-staggered.png",
bigger_staggered(),
40, 40,
20, 20,
color.White, color.Black,
pathGradient,
colorgrad.Warm(),
},
{
"Normal",
"../../out/normal_sol.png",
"normal.png",
normal(),
40, 40,
20, 20,
color.White, color.Black,
colorgrad.Warm(),
},
@ -58,7 +65,7 @@ func TestImageWriter(t *testing.T) {
for _, test := range tests {
writer := ImageWriter{
Filename: test.filename,
Filename: OUT_DIR + "/" + test.filename,
Maze: test.m,
CellWidth: test.CellWidth,
CellHeight: test.cellHeight,
@ -71,5 +78,45 @@ func TestImageWriter(t *testing.T) {
if err != nil {
t.Fatalf("%s: couldn't write solution, got following error\n%v", test.name, err)
}
assertEqualFile(t, EXPECTED_DIR+"/"+test.filename, OUT_DIR+"/"+test.filename, test.name)
os.Remove(writer.Filename)
}
os.Remove(OUT_DIR)
}
const chunkSize = 64000
func assertEqualFile(t *testing.T, file1, file2, name string) {
f1, err := os.Open(file1)
if err != nil {
t.Fatal(err)
}
defer f1.Close()
f2, err := os.Open(file2)
if err != nil {
t.Fatal(err)
}
defer f2.Close()
for {
b1 := make([]byte, chunkSize)
_, err1 := f1.Read(b1)
b2 := make([]byte, chunkSize)
_, err2 := f2.Read(b2)
if err1 != nil || err2 != nil {
if err1 == io.EOF && err2 == io.EOF {
return
} else if err1 == io.EOF || err2 == io.EOF {
t.Fatalf("%s: files are not equal. Got %q, wanted %q", name, file1, file2)
}
}
if !bytes.Equal(b1, b2) {
t.Fatalf("%s: files are not equal. Got %q, wanted %q", name, file1, file2)
}
}
}

View File

@ -1,7 +1,6 @@
package writer
import (
"fmt"
"maze-solver/maze"
"maze-solver/utils"
"testing"
@ -69,7 +68,6 @@ func TestStringsWriter(t *testing.T) {
}
for _, test := range tests {
fmt.Printf("----------- %s -----------\n", test.name)
writer := StringsWriter{
PathChar: test.pathChar,
WallChar: test.wallChar,

43
main.go
View File

@ -17,6 +17,28 @@ import (
)
func main() {
readerFactory, writerFactory, solverFactory, ok := parse_arguments()
if !ok {
return
}
defer utils.Timer("TOTAL", 1)()
reader := readerFactory.Get()
maze, err := parser.Parse(reader)
utils.Check(err, "Couldn't read maze")
solver := solverFactory.Get()
solved := solver.Solve(maze)
writer := writerFactory.Get(solved)
err = writer.Write()
utils.Check(err, "Couldn't write solved maze")
}
func parse_arguments() (*reader.ReaderFactory, *writer.WriterFactory, *solver.SolverFactory, bool) {
argparser := argparse.NewParser("maze-solver", "Solves the given maze (insane, right? who would've guessed?)")
var verboseLevel *int = argparser.FlagCounter("v", "verbose", &argparse.Options{
@ -109,12 +131,12 @@ func main() {
cellSizeIn := argparser.Int("", "cell-size-in", &argparse.Options{
Help: "Size of a cell (in pixels) for input file of image type",
Default: 20,
Default: 3,
})
cellSizeOut := argparser.Int("", "cell-size-out", &argparse.Options{
Help: "Size of a cell (in pixels) for output file of image type",
Default: 20,
Default: 3,
})
solverFactory.Type = argparser.Selector("a", "algo", solver.TYPES, &argparse.Options{
@ -124,7 +146,7 @@ func main() {
if err := argparser.Parse(os.Args); err != nil {
fmt.Println(argparser.Usage(err))
return
return nil, nil, nil, false
}
utils.VERBOSE_LEVEL = *verboseLevel
@ -137,18 +159,5 @@ func main() {
writerFactory.PathColor = color.RGBA{255, 255, 255, 255}
writerFactory.SolutionGradient = colorgrad.Warm()
defer utils.Timer("TOTAL", 1)()
reader := readerFactory.Get()
maze, err := parser.Parse(reader)
utils.Check(err, "Couldn't read maze")
solver := solverFactory.Get()
solved := solver.Solve(maze)
writer := writerFactory.Get(solved)
err = writer.Write()
utils.Check(err, "Couldn't write solved maze")
return &readerFactory, &writerFactory, &solverFactory, true
}

View File

@ -30,6 +30,7 @@ type Node struct {
Coords Coordinates
Up, Down *Node
Left, Right *Node
Visited bool `default:"false"`
}
func NewNode(coords Coordinates) *Node {

View File

@ -42,7 +42,7 @@ func TestTextReadTrivial(t *testing.T) {
nodes[4].Up = nodes[3]
reader := reader.TextReader{
reader := &reader.TextReader{
Filename: "../../assets/trivial.txt",
PathChar: ' ',
WallChar: '#',
@ -107,7 +107,7 @@ func TestTextReadTrivialBigger(t *testing.T) {
nodes[4].Up = nodes[3]
reader := reader.TextReader{
reader := &reader.TextReader{
Filename: "../../assets/trivial-bigger.txt",
PathChar: ' ',
WallChar: '#',
@ -177,7 +177,7 @@ func TestTextReadTrivialBiggerStaggered(t *testing.T) {
nodes[5].Up = nodes[4]
reader := reader.TextReader{
reader := &reader.TextReader{
Filename: "../../assets/trivial-bigger-staggered.txt",
PathChar: ' ',
WallChar: '#',
@ -310,7 +310,7 @@ func TestTextReadNormal(t *testing.T) {
nodes[link.to].Left = nodes[link.from]
}
reader := reader.TextReader{
reader := &reader.TextReader{
Filename: "../../assets/normal.txt",
PathChar: ' ',
WallChar: '#',
@ -501,7 +501,7 @@ func TestTextReadNormal2(t *testing.T) {
nodes[link.to].Left = nodes[link.from]
}
reader := reader.TextReader{
reader := &reader.TextReader{
Filename: "../../assets/normal2.txt",
PathChar: ' ',
WallChar: '#',

66
solver/a-star.go Normal file
View File

@ -0,0 +1,66 @@
package solver
import (
"maze-solver/maze"
"maze-solver/utils"
"sort"
)
type AStarSolver struct {
dist_from_start map[*maze.Node]int
dist_from_end map[*maze.Node]int
parent map[*maze.Node]*maze.Node
stack sorted_stack
}
func (s *AStarSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("A* algorithm", 2)()
s.dist_from_start = make(map[*maze.Node]int, len(m.Nodes))
s.dist_from_end = make(map[*maze.Node]int, len(m.Nodes))
s.parent = make(map[*maze.Node]*maze.Node, len(m.Nodes))
current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1]
for _, node := range m.Nodes {
s.dist_from_start[node] = 0
s.dist_from_end[node] = int(node.Coords.Distance(end.Coords))
}
for current != end {
current.Visited = true
for _, child := range []*maze.Node{current.Left, current.Right, current.Up, current.Down} {
if child != nil {
dist := s.dist_from_start[current] + int(current.Coords.Distance(child.Coords))
if !child.Visited {
s.parent[child] = current
s.dist_from_start[child] = dist
s.stack.insert(child, &s.dist_from_end)
} else if s.dist_from_start[child] > dist {
s.parent[child] = current
s.dist_from_start[child] = dist
sort.Slice(s.stack, func(i, j int) bool {
return s.dist_from_end[s.stack[i]] < s.dist_from_end[s.stack[j]]
})
}
}
}
current = s.stack.pop()
}
solution := make([]*maze.Node, 0, len(m.Nodes))
for current != m.Nodes[0] {
solution = append(solution, current)
current = s.parent[current]
}
solution = append(solution, m.Nodes[0])
for i, j := 0, len(solution)-1; i < j; i, j = i+1, j-1 {
solution[i], solution[j] = solution[j], solution[i]
}
return &maze.SolvedMaze{
Maze: m,
Solution: solution,
}
}

View File

@ -1,9 +1,117 @@
package solver
import "maze-solver/maze"
import (
"errors"
"fmt"
"maze-solver/maze"
"maze-solver/utils"
"strings"
)
type Bfs struct{}
func (*Bfs) Solve(maze *maze.Maze) *maze.SolvedMaze {
return nil
type BFSSolver struct {
queue *Queue
}
type Queue struct {
head, tail *Element
}
type Element struct {
prev, next *Element
value []*maze.Node
}
func (q *Queue) enqueue(v []*maze.Node) {
prev_last := q.tail
new_elem := &Element{
prev: prev_last,
next: nil,
value: v,
}
if prev_last != nil {
prev_last.next = new_elem
}
q.tail = new_elem
if q.head == nil {
q.head = new_elem
}
}
func (q *Queue) dequeue() ([]*maze.Node, error) {
if q.head == nil {
return nil, errors.New("Can't dequeue and empty queue")
}
ret := q.head.value
q.head = q.head.next
if q.head != nil {
q.head.prev = nil
} else {
q.tail = nil
}
return ret, nil
}
func (q Queue) String() string {
var ret strings.Builder
i := 0
for history := q.head; history != nil; history = history.next {
ret.WriteString(fmt.Sprintf("%v: %v\n", i, history_str(history.value)))
i++
}
return ret.String()
}
func history_str(history []*maze.Node) string {
var ret strings.Builder
for _, node := range history {
ret.WriteString(fmt.Sprintf("%v ", node.Coords))
}
return ret.String()
}
func (s *BFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("BFS algorithm", 2)()
current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1]
s.queue = &Queue{
head: nil,
tail: nil,
}
current_history := make([]*maze.Node, 0, len(m.Nodes))
current_history = append(current_history, current)
var err error
for current != end {
current.Visited = true
s.addIfNotVisited(current.Down, current_history)
s.addIfNotVisited(current.Left, current_history)
s.addIfNotVisited(current.Right, current_history)
s.addIfNotVisited(current.Up, current_history)
current_history, err = s.queue.dequeue()
if err != nil {
panic(err)
}
current = current_history[len(current_history)-1]
}
return &maze.SolvedMaze{
Maze: m,
Solution: current_history,
}
}
func (s *BFSSolver) addIfNotVisited(node *maze.Node, current_history []*maze.Node) {
if !visited(node) {
new_history := make([]*maze.Node, len(current_history)+1)
copy(new_history, current_history)
new_history[len(current_history)] = node
s.queue.enqueue(new_history)
}
}

View File

@ -5,27 +5,20 @@ import (
"maze-solver/utils"
)
type TurnLeftSolver struct {
visited map[*maze.Node]bool
}
type DFSSolver struct{}
func (s *TurnLeftSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("Turn left algorithm", 2)()
func (s *DFSSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("DFS algorithm", 2)()
current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1]
s.visited = make(map[*maze.Node]bool, len(m.Nodes))
for _, node := range m.Nodes {
s.visited[node] = false
}
stack := make([]*maze.Node, 0, len(m.Nodes))
stack = append(stack, current)
for current != end {
s.visited[current] = true
current.Visited = true
left_visited, right_visited, up_visited, down_visited := s.wasVisited(current.Left), s.wasVisited(current.Right), s.wasVisited(current.Up), s.wasVisited(current.Down)
left_visited, right_visited, up_visited, down_visited := visited(current.Left), visited(current.Right), visited(current.Up), visited(current.Down)
if left_visited && right_visited && up_visited && down_visited {
// dead end or no more visited nodes
@ -53,11 +46,3 @@ func (s *TurnLeftSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
}
return ret
}
func (s *TurnLeftSolver) wasVisited(node *maze.Node) bool {
if node == nil {
return true
}
visited, _ := s.visited[node]
return visited
}

63
solver/dijkstra.go Normal file
View File

@ -0,0 +1,63 @@
package solver
import (
"maze-solver/maze"
"maze-solver/utils"
"sort"
)
type DijkstraSolver struct {
dist_from_start map[*maze.Node]int
parent map[*maze.Node]*maze.Node
stack sorted_stack
}
func (s *DijkstraSolver) Solve(m *maze.Maze) *maze.SolvedMaze {
defer utils.Timer("Dijkstra algorithm", 2)()
s.dist_from_start = make(map[*maze.Node]int, len(m.Nodes))
s.parent = make(map[*maze.Node]*maze.Node, len(m.Nodes))
for _, node := range m.Nodes {
s.dist_from_start[node] = 0
}
current, end := m.Nodes[0], m.Nodes[len(m.Nodes)-1]
for current != end {
current.Visited = true
for _, child := range []*maze.Node{current.Left, current.Right, current.Up, current.Down} {
if child != nil {
dist := s.dist_from_start[current] + int(current.Coords.Distance(child.Coords))
if !child.Visited {
s.parent[child] = current
s.dist_from_start[child] = dist
s.stack.insert(child, &s.dist_from_start)
} else if s.dist_from_start[child] > dist {
s.parent[child] = current
s.dist_from_start[child] = dist
sort.Slice(s.stack, func(i, j int) bool {
return s.dist_from_start[s.stack[i]] < s.dist_from_start[s.stack[j]]
})
}
}
}
current = s.stack.pop()
}
solution := make([]*maze.Node, 0, len(m.Nodes))
for current != m.Nodes[0] {
solution = append(solution, current)
current = s.parent[current]
}
solution = append(solution, m.Nodes[0])
for i, j := 0, len(solution)-1; i < j; i, j = i+1, j-1 {
solution[i], solution[j] = solution[j], solution[i]
}
return &maze.SolvedMaze{
Maze: m,
Solution: solution,
}
}

View File

@ -14,17 +14,33 @@ type SolverFactory struct {
}
const (
_TURN_LEFT = "turn-left"
_DFS = "dfs"
_BFS = "bfs"
_Dijkstra = "dijkstra"
_AStar = "a-star"
)
var TYPES = []string{
_TURN_LEFT,
_DFS,
_BFS,
_Dijkstra,
_AStar,
}
func (f *SolverFactory) Get() Solver {
switch *f.Type {
case _TURN_LEFT:
return &TurnLeftSolver{}
case _DFS:
return &DFSSolver{}
case _BFS:
return &BFSSolver{}
case _AStar:
return &AStarSolver{}
case _Dijkstra:
return &DijkstraSolver{}
}
panic(fmt.Sprintf("Unrecognized solver type %q", *f.Type))
}
func visited(node *maze.Node) bool {
return node == nil || node.Visited
}

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
}