chore(day17): implent A* path finder #19

Merged
xuu merged 1 commits from day17-astar into main 2024-01-01 09:45:40 -07:00
7 changed files with 261 additions and 145 deletions

View File

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

View File

@ -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,8 +34,10 @@ func run(scan *bufio.Scanner) (*result, error) {
return &result, nil
}
func search(m aoc.Map[rune], minSteps, maxSteps int) int {
type direction int8
type Point = aoc.Point[int16]
type Map = aoc.Map[int16, rune]
// rotate for changing direction
type rotate int8
const (
@ -43,95 +45,135 @@ func search(m aoc.Map[rune], minSteps, maxSteps int) int {
CCW rotate = -1
)
// diretion of path steps
type direction int8
var (
U = aoc.Point{-1, 0}
R = aoc.Point{0, 1}
D = aoc.Point{1, 0}
L = aoc.Point{0, -1}
U = Point{-1, 0}
R = Point{0, 1}
D = Point{1, 0}
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))
for k, v := range Direction {
Directions[v] = direction(k)
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}
// position on the map
type position struct {
loc aoc.Point
direction aoc.Point
steps int
loc Point
direction Point
steps int8
}
step := func(p position) position {
func (p position) step() 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])
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}
}
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
// implements FindPath graph interface
type graph struct {
min, max int8
m Map
target Point
reads int
}
pq := aoc.PriorityQueue(less)
pq.Enqueue(memo{position: position{direction: D}})
pq.Enqueue(memo{position: position{direction: R}})
visited := aoc.Set[position]()
// Neighbors returns valid steps from given position. if at target returns none.
func (g *graph) Neighbors(current position) []position {
var nbs []position
for !pq.IsEmpty() {
current, _ := pq.Dequeue()
if current.loc == target && current.steps >= minSteps {
return current.cost
if current.steps == 0 {
return []position{
{R, R, 1},
{D, D, 1},
}
}
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)
}
// 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("*")
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})
fmt.Print(".")
}
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
fmt.Println("")
}

View File

@ -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)

View File

@ -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 {

View File

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

20
math.go
View File

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

View File

@ -1,12 +1,15 @@
package aoc
import (
"fmt"
"sort"
)
type priorityQueue[T any, U []T] struct {
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(&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
}