replacing dijkstra with a* didn't speed it up...

This commit is contained in:
2024-12-18 00:36:14 -08:00
parent 99fdb31d76
commit e35da0cd55

View File

@@ -23,29 +23,34 @@ struct Map : CustomStringConvertible {
let top = " \u{001B}[4m" + (0..<w).map { " \($0 % 10)" }.joined() + "\u{001B}[0m\n"
let maze = (0..<h).map { i in
String(format: "%2d▕", i) + (0..<w).map { j in
walls.contains(Coord(x: j, y: i)) ? "██" : " "
walls.contains(Coord(x: j, y: i)) ? "▓▓" : " "
}.joined() + ""
}.joined(separator: "\n")
let bot = "\n " + String(repeating: "🬂", count: w*2) + "🬀"
return top + maze + bot
}
func dijkstra(from start: Coord, to end: Coord) -> Int? {
func heur(_ a: Coord, _ b: Coord) -> Int {
return abs(a.x - b.x) + abs(a.y - b.y)
}
func astar(from start: Coord, to end: Coord) -> Int? {
var q = Heap<(Coord, Int)>(comparator: { l, r in l.1 < r.1 })
var seen: Set<Coord> = [start]
q.insert((start, 0))
while let (cell, cost) = q.pop() {
var seen: [Coord: Int] = [start: 0]
q.insert((start, heur(start, end)))
while let (cell, _) = q.pop() {
if cell == end {
return cost
return seen[cell]
}
[(0, -1), (0, 1), (-1, 0), (1, 0)].map { dy, dx in
Coord(x: cell.x + dx, y: cell.y + dy)}
.filter { c in c.x >= 0 && c.y >= 0 && c.x < w && c.y < h }
.filter { !seen.contains($0) }
.filter { !walls.contains($0) }
.forEach { neighbor in
seen.insert(neighbor)
q.insert((neighbor, cost + 1))
.forEach { nb in
let newCost = seen[cell]! + 1
if seen[nb, default: w*h] > newCost {
seen[nb] = newCost
q.insert((nb, newCost + heur(nb, end)))
}
}
}
return nil
@@ -58,9 +63,10 @@ struct AoC {
let bytes = try readInput(CommandLine.arguments[1])
let w = Int(CommandLine.arguments[2]) ?? 71
let h = Int(CommandLine.arguments[3]) ?? 71
for limit in 1024..<bytes.count {
let startLimit = Int(CommandLine.arguments[4]) ?? 1024
for limit in startLimit..<bytes.count {
let map = Map(walls: Set(bytes.prefix(limit)), w: w, h: h)
if let cost = map.dijkstra(
if let cost = map.astar(
from: Coord(x: 0, y: 0),
to: Coord(x: map.w - 1, y: map.h - 1)
) {