From 86f2f7a6f2760871af2b32af8a3f4297d8ab0764 Mon Sep 17 00:00:00 2001 From: xuu Date: Mon, 1 Jan 2024 09:26:31 -0700 Subject: [PATCH 1/6] chore(day17): implent A* path finder --- aoc_test.go | 17 +--- day17/main.go | 232 ++++++++++++++++++++++++++------------------- day17/main_test.go | 4 +- day18/main.go | 4 +- grids.go | 30 +++--- math.go | 20 ++-- search.go | 99 +++++++++++++++++-- 7 files changed, 261 insertions(+), 145 deletions(-) diff --git a/aoc_test.go b/aoc_test.go index 08c7932..7e9d5a1 100644 --- a/aoc_test.go +++ b/aoc_test.go @@ -86,7 +86,7 @@ func TestPriorityQueue(t *testing.T) { type elem [2]int less := func(a, b elem) bool { - return b[0] < a[0] + return a[0] < b[0] } pq := aoc.PriorityQueue(less) @@ -135,25 +135,12 @@ func TestSet(t *testing.T) { is.Equal(items, []int{1, 2, 3, 4}) } -// func TestGraph(t *testing.T) { -// g := aoc.Graph[int, uint](7) -// g.AddEdge(0, 1, 2) -// g.AddEdge(0, 2, 6) -// g.AddEdge(1, 3, 5) -// g.AddEdge(2, 3, 8) -// g.AddEdge(3, 4, 10) -// g.AddEdge(3, 5, 15) -// g.AddEdge(4, 6, 2) -// g.AddEdge(5, 6, 6) -// // g.Dijkstra(0) -// } - func ExamplePriorityQueue() { type memo struct { pt int score int } - less := func(a, b memo) bool { return a.score < b.score } + less := func(a, b memo) bool { return b.score < a.score } adj := map[int][][2]int{ 0: {{1, 2}, {2, 6}}, diff --git a/day17/main.go b/day17/main.go index 13c736f..54982ba 100644 --- a/day17/main.go +++ b/day17/main.go @@ -20,7 +20,7 @@ type result struct { func (r result) String() string { return fmt.Sprintf("%#v", r) } func run(scan *bufio.Scanner) (*result, error) { - var m aoc.Map[rune] + var m aoc.Map[int16, rune] for scan.Scan() { text := scan.Text() @@ -34,104 +34,146 @@ func run(scan *bufio.Scanner) (*result, error) { return &result, nil } -func search(m aoc.Map[rune], minSteps, maxSteps int) int { - type direction int8 - type rotate int8 +type Point = aoc.Point[int16] +type Map = aoc.Map[int16, rune] - const ( - CW rotate = 1 - CCW rotate = -1 - ) +// rotate for changing direction +type rotate int8 - var ( - U = aoc.Point{-1, 0} - R = aoc.Point{0, 1} - D = aoc.Point{1, 0} - L = aoc.Point{0, -1} - ) +const ( + CW rotate = 1 + CCW rotate = -1 +) - var Direction = []aoc.Point{U, R, D, L} +// diretion of path steps +type direction int8 - var Directions = make(map[aoc.Point]direction, len(Direction)) - for k, v := range Direction { - Directions[v] = direction(k) +var ( + U = Point{-1, 0} + R = Point{0, 1} + D = Point{1, 0} + L = Point{0, -1} +) + +var directions = []Point{U, R, D, L} + +var directionIDX = func() map[Point]direction { + m := make(map[Point]direction, len(directions)) + for k, v := range directions { + m[v] = direction(k) } + return m +}() - rows, cols := m.Size() - target := aoc.Point{rows - 1, cols - 1} - - type position struct { - loc aoc.Point - direction aoc.Point - steps int - } - - step := func(p position) position { - return position{p.loc.Add(p.direction), p.direction, p.steps + 1} - } - rotateAndStep := func(p position, towards rotate) position { - d := Direction[(int8(Directions[p.direction])+int8(towards)+4)%4] - // fmt.Println(towards, Directions[p.direction], "->", Directions[d]) - return position{p.loc.Add(d), d, 1} - } - - type memo struct { - cost int - position - } - less := func(a, b memo) bool { - if a.cost != b.cost { - return a.cost < b.cost - } - if a.position.loc != b.position.loc { - return b.position.loc.Less(a.position.loc) - } - if a.position.direction != b.position.direction { - return b.position.direction.Less(a.position.direction) - } - return a.steps < b.steps - } - - pq := aoc.PriorityQueue(less) - pq.Enqueue(memo{position: position{direction: D}}) - pq.Enqueue(memo{position: position{direction: R}}) - visited := aoc.Set[position]() - - for !pq.IsEmpty() { - current, _ := pq.Dequeue() - - if current.loc == target && current.steps >= minSteps { - return current.cost - } - - seen := position{loc: current.loc, direction: current.direction, steps: current.steps} - - if visited.Has(seen) { - // fmt.Println("visited", seen) - continue - } - visited.Add(seen) - - // fmt.Print("\033[2J\033[H") - // fmt.Println("step ", current.steps, " dir ", Directions[current.direction], " steps ", " score ", current.cost, current.loc) - - if left := rotateAndStep(current.position, CCW); current.steps >= minSteps && m.Valid(left.loc) { - _, cost, _ := m.Get(left.loc) - // fmt.Println("turn left", current, left) - pq.Enqueue(memo{cost: current.cost + int(cost-'0'), position: left}) - } - - if right := rotateAndStep(current.position, CW); current.steps >= minSteps && m.Valid(right.loc) { - _, cost, _ := m.Get(right.loc) - // fmt.Println("turn right", current, right) - pq.Enqueue(memo{cost: current.cost + int(cost-'0'), position: right}) - } - - if forward := step(current.position); current.steps < maxSteps && m.Valid(forward.loc) { - _, cost, _ := m.Get(forward.loc) - // fmt.Println("go forward", current, forward) - pq.Enqueue(memo{cost: current.cost + int(cost-'0'), position: forward}) - } - } - return -1 +// position on the map +type position struct { + loc Point + direction Point + steps int8 +} + +func (p position) step() position { + return position{p.loc.Add(p.direction), p.direction, p.steps + 1} +} +func (p position) rotateAndStep(towards rotate) position { + d := directions[(int8(directionIDX[p.direction])+int8(towards)+4)%4] + return position{p.loc.Add(d), d, 1} +} + +// implements FindPath graph interface +type graph struct { + min, max int8 + m Map + target Point + reads int +} + +// Neighbors returns valid steps from given position. if at target returns none. +func (g *graph) Neighbors(current position) []position { + var nbs []position + + if current.steps == 0 { + return []position{ + {R, R, 1}, + {D, D, 1}, + } + } + + if current.loc == g.target { + return nil + } + + if left := current.rotateAndStep(CCW); current.steps >= g.min && g.m.Valid(left.loc) { + nbs = append(nbs, left) + } + + if right := current.rotateAndStep(CW); current.steps >= g.min && g.m.Valid(right.loc) { + nbs = append(nbs, right) + } + + if forward := current.step(); current.steps < g.max && g.m.Valid(forward.loc) { + nbs = append(nbs, forward) + } + return nbs +} + +// Cost calculates heat cost to neighbor from map +func (g *graph) Cost(a, b position) int16 { + g.reads++ + _, r, _ := g.m.Get(b.loc) + return int16(r - '0') +} + +// Potential calculates distance to target +func (g *graph) Potential(a, b position) int16 { + return aoc.ManhattanDistance(a.loc, b.loc) +} + +// Seen attempt at simplifying the seen to use horizontal/vertical and no steps. +// It returns correct for part1 but not part 2.. +// func (g *pather) Seen(a position) position { +// if a.direction == U { +// a.direction = D +// } +// if a.direction == L { +// a.direction = R +// } +// a.steps = 0 +// return a +// } + +func search(m Map, minSteps, maxSteps int8) int { + rows, cols := m.Size() + start := Point{} + target := Point{rows - 1, cols - 1} + + g := graph{min: minSteps, max: maxSteps, m: m, target: target} + cost, path := aoc.FindPath[int16, position](&g, position{loc: start}, position{loc: target}) + + fmt.Println("total map reads = ", g.reads) + printGraph(m, path) + + return int(cost) +} + +// printGraph with the path overlay +func printGraph(m Map, path []position) { + pts := make(map[Point]position, len(path)) + for _, pt := range path { + pts[pt.loc] = pt + } + + for r, row := range m { + for c := range row { + if _, ok := pts[Point{int16(r), int16(c)}]; ok { + fmt.Print("*") + + continue + } + + fmt.Print(".") + } + fmt.Println("") + } + fmt.Println("") } diff --git a/day17/main_test.go b/day17/main_test.go index 64e490d..ea3a69c 100644 --- a/day17/main_test.go +++ b/day17/main_test.go @@ -13,8 +13,8 @@ import ( //go:embed example.txt var example []byte -//go:embed input.txt -var input []byte +// //go:embed input.txt +// var input []byte func TestExample(t *testing.T) { is := is.New(t) diff --git a/day18/main.go b/day18/main.go index 0d7bff0..bb12103 100644 --- a/day18/main.go +++ b/day18/main.go @@ -45,7 +45,7 @@ func run(scan *bufio.Scanner) (*result, error) { }, nil } -var OFFSET = map[string]aoc.Point{ +var OFFSET = map[string]aoc.Point[int]{ "R": {0, 1}, "D": {1, 0}, "L": {0, -1}, @@ -77,7 +77,7 @@ func fromColor(c string) aoc.Vector { } func findArea(vecs []aoc.Vector) int { - shoelace := []aoc.Point{{0, 0}} + shoelace := []aoc.Point[int]{{0, 0}} borderLength := 0 for _, vec := range vecs { diff --git a/grids.go b/grids.go index c66b6ce..22df4ed 100644 --- a/grids.go +++ b/grids.go @@ -1,23 +1,23 @@ package aoc type Vector struct { - Offset Point + Offset Point[int] Scale int } -func (v Vector) Point() Point { +func (v Vector) Point() Point[int] { return v.Offset.Scale(v.Scale) } -type Point [2]int +type Point[T integer] [2]T -func (p Point) Add(a Point) Point { - return Point{p[0] + a[0], p[1] + a[1]} +func (p Point[T]) Add(a Point[T]) Point[T] { + return Point[T]{p[0] + a[0], p[1] + a[1]} } -func (p Point) Scale(m int) Point { - return Point{p[0] * m, p[1] * m} +func (p Point[T]) Scale(m T) Point[T] { + return Point[T]{p[0] * m, p[1] * m} } -func (p Point) Less(b Point) bool { +func (p Point[T]) Less(b Point[T]) bool { if p[0] != b[0] { return p[0] < b[0] } @@ -41,7 +41,7 @@ func Transpose[T any](matrix [][]T) [][]T { } // NumPoints the number of the points inside an outline plus the number of points in the outline -func NumPoints(outline []Point, borderLength int) int { +func NumPoints(outline []Point[int], borderLength int) int { // shoelace - find the float area in a shape sum := 0 for _, p := range Pairwise(outline) { @@ -56,23 +56,23 @@ func NumPoints(outline []Point, borderLength int) int { return (ABS(area) - borderLength/2 + 1) + borderLength } -type Map[T any] [][]T +type Map[I integer, T any] [][]T -func (m *Map[T]) Get(p Point) (Point, T, bool) { +func (m *Map[I,T]) Get(p Point[I]) (Point[I], T, bool) { var zero T if !m.Valid(p) { - return [2]int{0, 0}, zero, false + return [2]I{0, 0}, zero, false } return p, (*m)[p[0]][p[1]], true } -func (m *Map[T]) Size() (int, int) { +func (m *Map[I,T]) Size() (I, I) { if m == nil || len(*m) == 0 { return 0, 0 } - return len(*m), len((*m)[0]) + return I(len(*m)), I(len((*m)[0])) } -func (m *Map[T]) Valid(p Point) bool { +func (m *Map[I,T]) Valid(p Point[I]) bool { rows, cols := m.Size() return p[0] >= 0 && p[0] < rows && p[1] >= 0 && p[1] < cols } diff --git a/math.go b/math.go index b6d1124..b86d6e1 100644 --- a/math.go +++ b/math.go @@ -3,19 +3,19 @@ package aoc import "cmp" type uinteger interface { - uint | uint8 | uint16 | uint32 | uint64 + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 } type sinteger interface { - int | int8 | int16 | int32 | int64 + ~int | ~int8 | ~int16 | ~int32 | ~int64 } type integer interface { sinteger | uinteger } -// type float interface { -// complex64 | complex128 | float32 | float64 -// } -// type number interface{ integer | float } +type float interface { + complex64 | complex128 | float32 | float64 +} +type number interface{ integer | float } // greatest common divisor (GCD) via Euclidean algorithm func GCD[T integer](a, b T) T { @@ -46,17 +46,17 @@ func LCM[T integer](integers ...T) T { return result } -func Sum[T integer](arr ...T) T { +func Sum[T number](arr ...T) T { var acc T for _, a := range arr { acc += a } return acc } -func SumFunc[T any, U integer](fn func(T) U, input ...T) U { +func SumFunc[T any, U number](fn func(T) U, input ...T) U { return Sum(SliceMap(fn, input...)...) } -func SumIFunc[T any, U integer](fn func(int, T) U, input ...T) U { +func SumIFunc[T any, U number](fn func(int, T) U, input ...T) U { return Sum(SliceIMap(fn, input...)...) } @@ -71,7 +71,7 @@ func Power2(n int) int { return p } -func ABS(i int) int { +func ABS[I integer](i I) I { if i < 0 { return -i } diff --git a/search.go b/search.go index 9b78695..f4ba47c 100644 --- a/search.go +++ b/search.go @@ -1,12 +1,15 @@ package aoc import ( + "fmt" "sort" ) type priorityQueue[T any, U []T] struct { - elems U - less func(a, b T) bool + elems U + less func(a, b T) bool + maxDepth int + totalEnqueue int } func PriorityQueue[T any, U []T](less func(a, b T) bool) *priorityQueue[T, U] { @@ -14,7 +17,9 @@ func PriorityQueue[T any, U []T](less func(a, b T) bool) *priorityQueue[T, U] { } func (pq *priorityQueue[T, U]) Enqueue(elem T) { pq.elems = append(pq.elems, elem) - sort.Slice(pq.elems, func(i, j int) bool { return pq.less(pq.elems[j], pq.elems[i]) }) + pq.totalEnqueue++ + pq.maxDepth = max(pq.maxDepth, len(pq.elems)) + sort.Slice(pq.elems, func(i, j int) bool { return pq.less(pq.elems[i], pq.elems[j]) }) } func (pq *priorityQueue[T, I]) IsEmpty() bool { return len(pq.elems) == 0 @@ -29,7 +34,89 @@ func (pq *priorityQueue[T, I]) Dequeue() (T, bool) { return elem, true } -type DS[T comparable] struct { - *priorityQueue[T, []T] - *set[T] +func ManhattanDistance[T integer](a, b Point[T]) T { + return ABS(a[1]-b[1]) + ABS(a[0]-b[0]) +} + +type pather[C number, N any] interface { + Neighbors(N) []N + Cost(a, b N) C + Potential(a, b N) C + + // OPTIONAL: modify value used by seen pruning. + // Seen(N) N +} + +type Path[C number, N any] []N + +func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, N]) { + var zero C + closed := make(map[N]bool) + + type node struct { + cost C + potential C + parent *node + last N + } + + NewPath := func(n *node) []N { + var path []N + for n.parent != nil { + path = append(path, n.last) + n = n.parent + } + path = append(path, n.last) + + Reverse(path) + return path + } + + less := func(a, b node) bool { + return b.cost+b.potential < a.cost+a.potential + } + + pq := PriorityQueue(less) + pq.Enqueue(node{last: start}) + + defer func() { + fmt.Println("queue max depth = ", pq.maxDepth, "total enqueue = ", pq.totalEnqueue) + }() + + var seenFn = func(a N) N { return a } + if s, ok := g.(interface{ Seen(N) N }); ok { + seenFn = s.Seen + } + + for !pq.IsEmpty() { + current, _ := pq.Dequeue() + cost, potential, n := current.cost, current.potential, current.last + + seen := seenFn(n) + if closed[seen] { + continue + } + closed[seen] = true + + if cost > 0 && potential == zero { + return cost, NewPath(¤t) + } + + for _, nb := range g.Neighbors(n) { + seen := seenFn(nb) + if closed[seen] { + continue + } + + cost := g.Cost(n, nb) + current.cost + nextPath := node{ + last: nb, + parent: ¤t, + cost: cost, + potential: g.Potential(nb, end), + } + pq.Enqueue(nextPath) + } + } + return zero, nil } From 0d78959bea2a968c5cc17af90cb7e9dba7560403 Mon Sep 17 00:00:00 2001 From: xuu Date: Mon, 1 Jan 2024 09:57:08 -0700 Subject: [PATCH 2/6] chore(day17): fix missing changes --- day17/main.go | 9 ++++++++- search.go | 24 ++++++++++++++++-------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/day17/main.go b/day17/main.go index 54982ba..4eccdff 100644 --- a/day17/main.go +++ b/day17/main.go @@ -129,9 +129,16 @@ func (g *graph) Potential(a, b position) int16 { return aoc.ManhattanDistance(a.loc, b.loc) } +func (g *graph) Target(a position) bool { + if a.loc == g.target && a.steps >= g.min { + return true + } + return false +} + // Seen attempt at simplifying the seen to use horizontal/vertical and no steps. // It returns correct for part1 but not part 2.. -// func (g *pather) Seen(a position) position { +// func (g *graph) Seen(a position) position { // if a.direction == U { // a.direction = D // } diff --git a/search.go b/search.go index f4ba47c..82065a7 100644 --- a/search.go +++ b/search.go @@ -43,8 +43,11 @@ type pather[C number, N any] interface { Cost(a, b N) C Potential(a, b N) C - // OPTIONAL: modify value used by seen pruning. + // OPTIONAL: + // Seen modify value used by seen pruning. // Seen(N) N + // Target returns true if target reached. + // Target(N) bool } type Path[C number, N any] []N @@ -57,16 +60,16 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, cost C potential C parent *node - last N + position N } NewPath := func(n *node) []N { var path []N for n.parent != nil { - path = append(path, n.last) + path = append(path, n.position) n = n.parent } - path = append(path, n.last) + path = append(path, n.position) Reverse(path) return path @@ -77,7 +80,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, } pq := PriorityQueue(less) - pq.Enqueue(node{last: start}) + pq.Enqueue(node{position: start}) defer func() { fmt.Println("queue max depth = ", pq.maxDepth, "total enqueue = ", pq.totalEnqueue) @@ -88,9 +91,14 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, seenFn = s.Seen } + var targetFn = func(a N) bool { return true } + if s, ok := g.(interface{ Target(N) bool }); ok { + targetFn = s.Target + } + for !pq.IsEmpty() { current, _ := pq.Dequeue() - cost, potential, n := current.cost, current.potential, current.last + cost, potential, n := current.cost, current.potential, current.position seen := seenFn(n) if closed[seen] { @@ -98,7 +106,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, } closed[seen] = true - if cost > 0 && potential == zero { + if cost > 0 && potential == zero && targetFn(current.position) { return cost, NewPath(¤t) } @@ -110,7 +118,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, cost := g.Cost(n, nb) + current.cost nextPath := node{ - last: nb, + position: nb, parent: ¤t, cost: cost, potential: g.Potential(nb, end), From fd85530d882322af93784fb087dbf956ad8234cf Mon Sep 17 00:00:00 2001 From: xuu Date: Mon, 1 Jan 2024 10:59:40 -0700 Subject: [PATCH 3/6] chore(day17): simplify interfaces. add docs --- search.go | 51 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/search.go b/search.go index 82065a7..278e794 100644 --- a/search.go +++ b/search.go @@ -1,44 +1,52 @@ package aoc import ( - "fmt" "sort" ) -type priorityQueue[T any, U []T] struct { - elems U +type priorityQueue[T any] struct { + elems []T less func(a, b T) bool maxDepth int totalEnqueue int + totalDequeue int } -func PriorityQueue[T any, U []T](less func(a, b T) bool) *priorityQueue[T, U] { - return &priorityQueue[T, U]{less: less} +// PriorityQueue implements a simple slice based queue. +// less is the function for sorting. reverse a and b to reverse the sort. +// T is the item +// U is a slice of T +func PriorityQueue[T any](less func(a, b T) bool) *priorityQueue[T] { + return &priorityQueue[T]{less: less} } -func (pq *priorityQueue[T, U]) Enqueue(elem T) { - pq.elems = append(pq.elems, elem) +func (pq *priorityQueue[T]) Enqueue(elem T) { pq.totalEnqueue++ + + pq.elems = append(pq.elems, elem) pq.maxDepth = max(pq.maxDepth, len(pq.elems)) - sort.Slice(pq.elems, func(i, j int) bool { return pq.less(pq.elems[i], pq.elems[j]) }) } -func (pq *priorityQueue[T, I]) IsEmpty() bool { +func (pq *priorityQueue[T]) IsEmpty() bool { return len(pq.elems) == 0 } -func (pq *priorityQueue[T, I]) Dequeue() (T, bool) { +func (pq *priorityQueue[T]) Dequeue() (T, bool) { + pq.totalDequeue++ + var elem T if pq.IsEmpty() { return elem, false } + sort.Slice(pq.elems, func(i, j int) bool { return pq.less(pq.elems[i], pq.elems[j]) }) pq.elems, elem = pq.elems[:len(pq.elems)-1], pq.elems[len(pq.elems)-1] return elem, true } +// ManhattanDistance the distance between two points measured along axes at right angles. func ManhattanDistance[T integer](a, b Point[T]) T { return ABS(a[1]-b[1]) + ABS(a[0]-b[0]) } -type pather[C number, N any] interface { +type pather[C number, N comparable] interface { Neighbors(N) []N Cost(a, b N) C Potential(a, b N) C @@ -46,15 +54,20 @@ type pather[C number, N any] interface { // OPTIONAL: // Seen modify value used by seen pruning. // Seen(N) N + // Target returns true if target reached. // Target(N) bool } -type Path[C number, N any] []N - -func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, N]) { +// FindPath uses the A* path finding algorithem. +// g is the graph source that implements the pather interface. +// C is an numeric type for calculating cost/potential +// N is the node values. is comparable for storing in visited table for pruning. +// start, end are nodes that dileniate the start and end of the search path. +// The returned values are the calculated cost and the path taken from start to end. +func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, []N) { var zero C - closed := make(map[N]bool) + visited := make(map[N]bool) type node struct { cost C @@ -83,7 +96,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, pq.Enqueue(node{position: start}) defer func() { - fmt.Println("queue max depth = ", pq.maxDepth, "total enqueue = ", pq.totalEnqueue) + Log("queue max depth = ", pq.maxDepth, "total enqueue = ", pq.totalEnqueue, "total dequeue = ", pq.totalDequeue) }() var seenFn = func(a N) N { return a } @@ -101,10 +114,10 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, cost, potential, n := current.cost, current.potential, current.position seen := seenFn(n) - if closed[seen] { + if visited[seen] { continue } - closed[seen] = true + visited[seen] = true if cost > 0 && potential == zero && targetFn(current.position) { return cost, NewPath(¤t) @@ -112,7 +125,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, Path[C, for _, nb := range g.Neighbors(n) { seen := seenFn(nb) - if closed[seen] { + if visited[seen] { continue } From adc01f4df97b3a0fdd9d8a079b771a9fc0b71b0a Mon Sep 17 00:00:00 2001 From: xuu Date: Mon, 1 Jan 2024 12:44:08 -0700 Subject: [PATCH 4/6] chore(day17): log output --- day17/main.go | 8 ++++++-- runner.go | 6 +++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/day17/main.go b/day17/main.go index 4eccdff..f63b8da 100644 --- a/day17/main.go +++ b/day17/main.go @@ -8,7 +8,7 @@ import ( aoc "go.sour.is/advent-of-code" ) -// var log = aoc.Log +var log = aoc.Log func main() { aoc.MustResult(aoc.Runner(run)) } @@ -26,10 +26,14 @@ func run(scan *bufio.Scanner) (*result, error) { text := scan.Text() m = append(m, []rune(text)) } + log("start day 17") result := result{} result.valuePT1 = search(m, 1, 3) + log("result from part 1 = ", result.valuePT1) + result.valuePT2 = search(m, 4, 10) + log("result from part 2 = ", result.valuePT2) return &result, nil } @@ -157,7 +161,7 @@ func search(m Map, minSteps, maxSteps int8) int { g := graph{min: minSteps, max: maxSteps, m: m, target: target} cost, path := aoc.FindPath[int16, position](&g, position{loc: start}, position{loc: target}) - fmt.Println("total map reads = ", g.reads) + log("total map reads = ", g.reads) printGraph(m, path) return int(cost) diff --git a/runner.go b/runner.go index 5958633..d2600aa 100644 --- a/runner.go +++ b/runner.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "strings" + "time" ) func Runner[R any, F func(*bufio.Scanner) (R, error)](run F) (R, error) { @@ -33,7 +34,10 @@ func MustResult[T any](result T, err error) { Log("result", result) } -func Log(v ...any) { fmt.Fprintln(os.Stderr, v...) } +func Log(v ...any) { + fmt.Fprint(os.Stderr, time.Now(), ": ") + fmt.Fprintln(os.Stderr, v...) +} func Logf(format string, v ...any) { if !strings.HasSuffix(format, "\n") { format += "\n" From eb1eaaab43de11755c514f8b136e61e44676076b Mon Sep 17 00:00:00 2001 From: xuu Date: Mon, 1 Jan 2024 14:12:53 -0700 Subject: [PATCH 5/6] chore(day17): add open list for A* --- .gitea/workflows/test.yml | 2 +- day17/main_test.go | 22 +++++++++++----------- search.go | 21 ++++++++++++++------- 3 files changed, 26 insertions(+), 19 deletions(-) diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index 08ea354..4d34acf 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -28,6 +28,6 @@ jobs: go-version: 1.21.3 - name: Test - run: go test --race -cover ./... + run: go test -timeout 240s -race -cover ./... - run: echo "🍏 This job's status is ${{ job.status }}." diff --git a/day17/main_test.go b/day17/main_test.go index ea3a69c..d7fd635 100644 --- a/day17/main_test.go +++ b/day17/main_test.go @@ -13,8 +13,8 @@ import ( //go:embed example.txt var example []byte -// //go:embed input.txt -// var input []byte +//go:embed input.txt +var input []byte func TestExample(t *testing.T) { is := is.New(t) @@ -28,14 +28,14 @@ func TestExample(t *testing.T) { is.Equal(result.valuePT2, 94) } -// func TestSolution(t *testing.T) { -// is := is.New(t) -// scan := bufio.NewScanner(bytes.NewReader(input)) +func TestSolution(t *testing.T) { + is := is.New(t) + scan := bufio.NewScanner(bytes.NewReader(input)) -// result, err := run(scan) -// is.NoErr(err) + result, err := run(scan) + is.NoErr(err) -// t.Log(result) -// is.Equal(result.valuePT1, 843) -// is.Equal(result.valuePT2, 1017) -// } + t.Log(result) + is.Equal(result.valuePT1, 843) + is.Equal(result.valuePT2, 1017) +} diff --git a/search.go b/search.go index 278e794..a559129 100644 --- a/search.go +++ b/search.go @@ -61,13 +61,15 @@ type pather[C number, N comparable] interface { // FindPath uses the A* path finding algorithem. // g is the graph source that implements the pather interface. -// C is an numeric type for calculating cost/potential -// N is the node values. is comparable for storing in visited table for pruning. +// +// C is an numeric type for calculating cost/potential +// N is the node values. is comparable for storing in visited table for pruning. +// // start, end are nodes that dileniate the start and end of the search path. // The returned values are the calculated cost and the path taken from start to end. func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, []N) { var zero C - visited := make(map[N]bool) + closed := make(map[N]bool) type node struct { cost C @@ -94,6 +96,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, []N) { pq := PriorityQueue(less) pq.Enqueue(node{position: start}) + closed[start] = false defer func() { Log("queue max depth = ", pq.maxDepth, "total enqueue = ", pq.totalEnqueue, "total dequeue = ", pq.totalDequeue) @@ -114,10 +117,10 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, []N) { cost, potential, n := current.cost, current.potential, current.position seen := seenFn(n) - if visited[seen] { + if closed[seen] { continue } - visited[seen] = true + closed[seen] = true if cost > 0 && potential == zero && targetFn(current.position) { return cost, NewPath(¤t) @@ -125,7 +128,7 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, []N) { for _, nb := range g.Neighbors(n) { seen := seenFn(nb) - if visited[seen] { + if closed[seen] { continue } @@ -136,7 +139,11 @@ func FindPath[C integer, N comparable](g pather[C, N], start, end N) (C, []N) { cost: cost, potential: g.Potential(nb, end), } - pq.Enqueue(nextPath) + // check if path is in open list + if _, open := closed[seen]; !open { + pq.Enqueue(nextPath) + closed[seen] = false // add to open list + } } } return zero, nil From 2c959c109b8b40500b86767eaf3fb2b364ed2685 Mon Sep 17 00:00:00 2001 From: xuu Date: Mon, 1 Jan 2024 14:19:00 -0700 Subject: [PATCH 6/6] tests(day17): disable solution --- day17/main_test.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/day17/main_test.go b/day17/main_test.go index d7fd635..64e490d 100644 --- a/day17/main_test.go +++ b/day17/main_test.go @@ -28,14 +28,14 @@ func TestExample(t *testing.T) { is.Equal(result.valuePT2, 94) } -func TestSolution(t *testing.T) { - is := is.New(t) - scan := bufio.NewScanner(bytes.NewReader(input)) +// func TestSolution(t *testing.T) { +// is := is.New(t) +// scan := bufio.NewScanner(bytes.NewReader(input)) - result, err := run(scan) - is.NoErr(err) +// result, err := run(scan) +// is.NoErr(err) - t.Log(result) - is.Equal(result.valuePT1, 843) - is.Equal(result.valuePT2, 1017) -} +// t.Log(result) +// is.Equal(result.valuePT1, 843) +// is.Equal(result.valuePT2, 1017) +// }