chore(day17): implent A* path finder

This commit is contained in:
xuu 2024-01-01 09:26:31 -07:00
parent 378e403c1c
commit c99836bd2a
Signed by: xuu
GPG Key ID: 8B3B0604F164E04F
7 changed files with 276 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,8 +34,10 @@ 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]
// rotate for changing direction
type rotate int8 type rotate int8
const ( const (
@ -43,95 +45,142 @@ func search(m aoc.Map[rune], minSteps, maxSteps int) int {
CCW rotate = -1 CCW rotate = -1
) )
// diretion of path steps
type direction int8
var ( var (
U = aoc.Point{-1, 0} U = Point{-1, 0}
R = aoc.Point{0, 1} R = Point{0, 1}
D = aoc.Point{1, 0} D = Point{1, 0}
L = aoc.Point{0, -1} L = Point{0, -1}
) )
var Direction = []aoc.Point{U, R, D, L} var directions = []Point{U, R, D, L}
var Directions = make(map[aoc.Point]direction, len(Direction)) var directionIDX = func() map[Point]direction {
for k, v := range Direction { m := make(map[Point]direction, len(directions))
Directions[v] = direction(k) 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 { type position struct {
loc aoc.Point loc Point
direction aoc.Point direction Point
steps int steps int8
} }
step := func(p position) position { func (p position) step() position {
return position{p.loc.Add(p.direction), p.direction, p.steps + 1} return position{p.loc.Add(p.direction), p.direction, p.steps + 1}
} }
rotateAndStep := func(p position, towards rotate) position { func (p position) rotateAndStep(towards rotate) position {
d := Direction[(int8(Directions[p.direction])+int8(towards)+4)%4] d := directions[(int8(directionIDX[p.direction])+int8(towards)+4)%4]
// fmt.Println(towards, Directions[p.direction], "->", Directions[d])
return position{p.loc.Add(d), d, 1} return position{p.loc.Add(d), d, 1}
} }
type memo struct { // implements FindPath graph interface
cost int type graph struct {
position min, max int8
} m Map
less := func(a, b memo) bool { target Point
if a.cost != b.cost { reads int
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) // Neighbors returns valid steps from given position. if at target returns none.
pq.Enqueue(memo{position: position{direction: D}}) func (g *graph) Neighbors(current position) []position {
pq.Enqueue(memo{position: position{direction: R}}) var nbs []position
visited := aoc.Set[position]()
for !pq.IsEmpty() { if current.steps == 0 {
current, _ := pq.Dequeue() return []position{
{R, R, 1},
if current.loc == target && current.steps >= minSteps { {D, D, 1},
return current.cost }
} }
seen := position{loc: current.loc, direction: current.direction, steps: current.steps} 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)
}
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 *graph) 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("*")
if visited.Has(seen) {
// fmt.Println("visited", seen)
continue continue
} }
visited.Add(seen)
// fmt.Print("\033[2J\033[H") fmt.Print(".")
// 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})
} }
fmt.Println("")
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})
} }
fmt.Println("")
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
} }

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
} }

103
search.go
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,97 @@ 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:
// 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]) {
var zero C
closed := make(map[N]bool)
type node struct {
cost C
potential C
parent *node
position N
}
NewPath := func(n *node) []N {
var path []N
for n.parent != nil {
path = append(path, n.position)
n = n.parent
}
path = append(path, n.position)
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{position: 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
}
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.position
seen := seenFn(n)
if closed[seen] {
continue
}
closed[seen] = true
if cost > 0 && potential == zero && targetFn(current.position) {
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{
position: nb,
parent: &current,
cost: cost,
potential: g.Potential(nb, end),
}
pq.Enqueue(nextPath)
}
}
return zero, nil
} }