chore(day17): implent A* path finder
All checks were successful
Go Bump / bump (push) Successful in 8s
Go Test / build (pull_request) Successful in 51s
Go Test / build (push) Successful in 35s

This commit is contained in:
xuu 2024-01-01 09:26:31 -07:00
parent 378e403c1c
commit 86f2f7a6f2
Signed by: xuu
GPG Key ID: 8B3B0604F164E04F
7 changed files with 261 additions and 145 deletions

View File

@ -86,7 +86,7 @@ func TestPriorityQueue(t *testing.T) {
type elem [2]int type elem [2]int
less := func(a, b elem) bool { less := func(a, b elem) bool {
return b[0] < a[0] return a[0] < b[0]
} }
pq := aoc.PriorityQueue(less) pq := aoc.PriorityQueue(less)
@ -135,25 +135,12 @@ func TestSet(t *testing.T) {
is.Equal(items, []int{1, 2, 3, 4}) 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() { func ExamplePriorityQueue() {
type memo struct { type memo struct {
pt int pt int
score 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{ adj := map[int][][2]int{
0: {{1, 2}, {2, 6}}, 0: {{1, 2}, {2, 6}},

View File

@ -20,7 +20,7 @@ type result struct {
func (r result) String() string { return fmt.Sprintf("%#v", r) } func (r result) String() string { return fmt.Sprintf("%#v", r) }
func run(scan *bufio.Scanner) (*result, error) { func run(scan *bufio.Scanner) (*result, error) {
var m aoc.Map[rune] var m aoc.Map[int16, rune]
for scan.Scan() { for scan.Scan() {
text := scan.Text() text := scan.Text()
@ -34,104 +34,146 @@ func run(scan *bufio.Scanner) (*result, error) {
return &result, nil return &result, nil
} }
func search(m aoc.Map[rune], minSteps, maxSteps int) int { type Point = aoc.Point[int16]
type direction int8 type Map = aoc.Map[int16, rune]
type rotate int8
const ( // rotate for changing direction
CW rotate = 1 type rotate int8
CCW rotate = -1
)
var ( const (
U = aoc.Point{-1, 0} CW rotate = 1
R = aoc.Point{0, 1} CCW rotate = -1
D = aoc.Point{1, 0} )
L = aoc.Point{0, -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)) var (
for k, v := range Direction { U = Point{-1, 0}
Directions[v] = direction(k) 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() // position on the map
target := aoc.Point{rows - 1, cols - 1} type position struct {
loc Point
type position struct { direction Point
loc aoc.Point steps int8
direction aoc.Point }
steps int
} func (p position) step() position {
return position{p.loc.Add(p.direction), p.direction, p.steps + 1}
step := func(p position) 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]
rotateAndStep := func(p position, towards rotate) position { return position{p.loc.Add(d), d, 1}
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} // implements FindPath graph interface
} type graph struct {
min, max int8
type memo struct { m Map
cost int target Point
position reads int
} }
less := func(a, b memo) bool {
if a.cost != b.cost { // Neighbors returns valid steps from given position. if at target returns none.
return a.cost < b.cost func (g *graph) Neighbors(current position) []position {
} var nbs []position
if a.position.loc != b.position.loc {
return b.position.loc.Less(a.position.loc) if current.steps == 0 {
} return []position{
if a.position.direction != b.position.direction { {R, R, 1},
return b.position.direction.Less(a.position.direction) {D, D, 1},
} }
return a.steps < b.steps }
}
if current.loc == g.target {
pq := aoc.PriorityQueue(less) return nil
pq.Enqueue(memo{position: position{direction: D}}) }
pq.Enqueue(memo{position: position{direction: R}})
visited := aoc.Set[position]() if left := current.rotateAndStep(CCW); current.steps >= g.min && g.m.Valid(left.loc) {
nbs = append(nbs, left)
for !pq.IsEmpty() { }
current, _ := pq.Dequeue()
if right := current.rotateAndStep(CW); current.steps >= g.min && g.m.Valid(right.loc) {
if current.loc == target && current.steps >= minSteps { nbs = append(nbs, right)
return current.cost }
}
if forward := current.step(); current.steps < g.max && g.m.Valid(forward.loc) {
seen := position{loc: current.loc, direction: current.direction, steps: current.steps} nbs = append(nbs, forward)
}
if visited.Has(seen) { return nbs
// fmt.Println("visited", seen) }
continue
} // Cost calculates heat cost to neighbor from map
visited.Add(seen) func (g *graph) Cost(a, b position) int16 {
g.reads++
// fmt.Print("\033[2J\033[H") _, r, _ := g.m.Get(b.loc)
// fmt.Println("step ", current.steps, " dir ", Directions[current.direction], " steps ", " score ", current.cost, current.loc) return int16(r - '0')
}
if left := rotateAndStep(current.position, CCW); current.steps >= minSteps && m.Valid(left.loc) {
_, cost, _ := m.Get(left.loc) // Potential calculates distance to target
// fmt.Println("turn left", current, left) func (g *graph) Potential(a, b position) int16 {
pq.Enqueue(memo{cost: current.cost + int(cost-'0'), position: left}) return aoc.ManhattanDistance(a.loc, b.loc)
} }
if right := rotateAndStep(current.position, CW); current.steps >= minSteps && m.Valid(right.loc) { // Seen attempt at simplifying the seen to use horizontal/vertical and no steps.
_, cost, _ := m.Get(right.loc) // It returns correct for part1 but not part 2..
// fmt.Println("turn right", current, right) // func (g *pather) Seen(a position) position {
pq.Enqueue(memo{cost: current.cost + int(cost-'0'), position: right}) // if a.direction == U {
} // a.direction = D
// }
if forward := step(current.position); current.steps < maxSteps && m.Valid(forward.loc) { // if a.direction == L {
_, cost, _ := m.Get(forward.loc) // a.direction = R
// fmt.Println("go forward", current, forward) // }
pq.Enqueue(memo{cost: current.cost + int(cost-'0'), position: forward}) // a.steps = 0
} // return a
} // }
return -1
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("")
} }

View File

@ -13,8 +13,8 @@ import (
//go:embed example.txt //go:embed example.txt
var example []byte var example []byte
//go:embed input.txt // //go:embed input.txt
var input []byte // var input []byte
func TestExample(t *testing.T) { func TestExample(t *testing.T) {
is := is.New(t) is := is.New(t)

View File

@ -45,7 +45,7 @@ func run(scan *bufio.Scanner) (*result, error) {
}, nil }, nil
} }
var OFFSET = map[string]aoc.Point{ var OFFSET = map[string]aoc.Point[int]{
"R": {0, 1}, "R": {0, 1},
"D": {1, 0}, "D": {1, 0},
"L": {0, -1}, "L": {0, -1},
@ -77,7 +77,7 @@ func fromColor(c string) aoc.Vector {
} }
func findArea(vecs []aoc.Vector) int { func findArea(vecs []aoc.Vector) int {
shoelace := []aoc.Point{{0, 0}} shoelace := []aoc.Point[int]{{0, 0}}
borderLength := 0 borderLength := 0
for _, vec := range vecs { for _, vec := range vecs {

View File

@ -1,23 +1,23 @@
package aoc package aoc
type Vector struct { type Vector struct {
Offset Point Offset Point[int]
Scale int Scale int
} }
func (v Vector) Point() Point { func (v Vector) Point() Point[int] {
return v.Offset.Scale(v.Scale) return v.Offset.Scale(v.Scale)
} }
type Point [2]int type Point[T integer] [2]T
func (p Point) Add(a Point) Point { func (p Point[T]) Add(a Point[T]) Point[T] {
return Point{p[0] + a[0], p[1] + a[1]} return Point[T]{p[0] + a[0], p[1] + a[1]}
} }
func (p Point) Scale(m int) Point { func (p Point[T]) Scale(m T) Point[T] {
return Point{p[0] * m, p[1] * m} 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] { if p[0] != b[0] {
return 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 // 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 // shoelace - find the float area in a shape
sum := 0 sum := 0
for _, p := range Pairwise(outline) { for _, p := range Pairwise(outline) {
@ -56,23 +56,23 @@ func NumPoints(outline []Point, borderLength int) int {
return (ABS(area) - borderLength/2 + 1) + borderLength 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 var zero T
if !m.Valid(p) { 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 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 { if m == nil || len(*m) == 0 {
return 0, 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() rows, cols := m.Size()
return p[0] >= 0 && p[0] < rows && p[1] >= 0 && p[1] < cols return p[0] >= 0 && p[0] < rows && p[1] >= 0 && p[1] < cols
} }

20
math.go
View File

@ -3,19 +3,19 @@ package aoc
import "cmp" import "cmp"
type uinteger interface { type uinteger interface {
uint | uint8 | uint16 | uint32 | uint64 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
} }
type sinteger interface { type sinteger interface {
int | int8 | int16 | int32 | int64 ~int | ~int8 | ~int16 | ~int32 | ~int64
} }
type integer interface { type integer interface {
sinteger | uinteger sinteger | uinteger
} }
// type float interface { type float interface {
// complex64 | complex128 | float32 | float64 complex64 | complex128 | float32 | float64
// } }
// type number interface{ integer | float } type number interface{ integer | float }
// greatest common divisor (GCD) via Euclidean algorithm // greatest common divisor (GCD) via Euclidean algorithm
func GCD[T integer](a, b T) T { func GCD[T integer](a, b T) T {
@ -46,17 +46,17 @@ func LCM[T integer](integers ...T) T {
return result return result
} }
func Sum[T integer](arr ...T) T { func Sum[T number](arr ...T) T {
var acc T var acc T
for _, a := range arr { for _, a := range arr {
acc += a acc += a
} }
return acc 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...)...) 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...)...) return Sum(SliceIMap(fn, input...)...)
} }
@ -71,7 +71,7 @@ func Power2(n int) int {
return p return p
} }
func ABS(i int) int { func ABS[I integer](i I) I {
if i < 0 { if i < 0 {
return -i return -i
} }

View File

@ -1,12 +1,15 @@
package aoc package aoc
import ( import (
"fmt"
"sort" "sort"
) )
type priorityQueue[T any, U []T] struct { type priorityQueue[T any, U []T] struct {
elems U elems U
less func(a, b T) bool 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] { 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) { func (pq *priorityQueue[T, U]) Enqueue(elem T) {
pq.elems = append(pq.elems, elem) 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 { func (pq *priorityQueue[T, I]) IsEmpty() bool {
return len(pq.elems) == 0 return len(pq.elems) == 0
@ -29,7 +34,89 @@ func (pq *priorityQueue[T, I]) Dequeue() (T, bool) {
return elem, true return elem, true
} }
type DS[T comparable] struct { func ManhattanDistance[T integer](a, b Point[T]) T {
*priorityQueue[T, []T] return ABS(a[1]-b[1]) + ABS(a[0]-b[0])
*set[T] }
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(&current)
}
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: &current,
cost: cost,
potential: g.Potential(nb, end),
}
pq.Enqueue(nextPath)
}
}
return zero, nil
} }