Files
aoc24/day18/d18p2.swift
2024-12-17 23:39:19 -08:00

77 lines
2.5 KiB
Swift

import Foundation
struct Coord : Hashable, CustomStringConvertible {
let (x, y): (Int, Int)
var description: String { return "(\(x),\(y))" }
}
func readInput(_ fileName: String) throws -> [Coord] {
let xy = try Regex(#"([0-9]+),([0-9]+)"#)
return try String(contentsOfFile: fileName, encoding: .ascii)
.split(separator: "\n")
.compactMap { $0.wholeMatch(of: xy) }
.map { Coord(
x: Int($0.output[1].substring!)!,
y: Int($0.output[2].substring!)!
) }
}
struct Map : CustomStringConvertible {
let walls: Set<Coord>
let (w, h): (Int, Int)
var description: String {
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)) ? "██" : " "
}.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? {
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() {
if cell == end {
return cost
}
[(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))
}
}
return nil
}
}
@main
struct AoC {
static func main() throws {
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 map = Map(walls: Set(bytes.prefix(limit)), w: w, h: h)
if let cost = map.dijkstra(
from: Coord(x: 0, y: 0),
to: Coord(x: map.w - 1, y: map.h - 1)
) {
print("\(limit): \(cost)")
} else {
print(map)
print("found byte \(limit-1): \(bytes[limit-1])")
return
}
}
}
}