This commit is contained in:
2024-12-20 11:50:03 -08:00
parent ed04eb9a3d
commit 321540d1c1
2 changed files with 196 additions and 11 deletions

View File

@@ -20,21 +20,19 @@ struct Maze : CustomStringConvertible {
}
return s.map { $0.joined() + "\n" }.joined() + "\(start), \(end)"
}
let adjacents = [(-1, 0), (1, 0), (0, -1), (0, 1)]
func valid(_ cell: Coord) -> Bool {
return cell.x >= 0 && cell.x < w && cell.y >= 0 && cell.y < h &&
!walls.contains(cell)
}
func neighbor(of cell: Coord, isNot excluded: Coord) -> Coord {
return adjacents
func neighbors(of cell: Coord) -> [Coord] {
return [(-1, 0), (1, 0), (0, -1), (0, 1)]
.map { dx, dy in Coord(x: cell.x + dx, y: cell.y + dy) }
.filter { newCell in valid(newCell) && newCell != excluded }[0]
}
func cheats(of cell: Coord) -> [Coord] {
return adjacents
return [(-1, 0), (1, 0), (0, -1), (0, 1)]
.map { dx, dy in Coord(x: cell.x + dx*2, y: cell.y + dy*2) }
.filter(valid)
}
@@ -43,18 +41,18 @@ struct Maze : CustomStringConvertible {
var cost: [Coord: Int] = [start: 0]
var jumps: [(Coord, Coord)] = []
var cell = start
var prevCell = start
var prev = start
var currentCost = 0
while cell != end {
// list potential cheats from current cell
let newCheats = cheats(of: cell).filter { !cost.keys.contains($0) }
jumps.append(contentsOf: newCheats.map { dest in (cell, dest)} )
// add cost to table
let nextCell = neighbor(of: cell, isNot: prevCell)
let next = neighbors(of: cell).filter(valid).filter { $0 != prev }[0]
currentCost += 1
cost[nextCell] = currentCost
prevCell = cell
cell = nextCell
cost[next] = currentCost
prev = cell
cell = next
}
return jumps.map { from, to in cost[to]! - cost[from]! - 2 }
}
@@ -84,6 +82,7 @@ func readInput(_ filePath: String) throws -> Maze {
let maze = try readInput(CommandLine.arguments[1])
print(maze)
let cheats = maze.cheats()
print(cheats.reduce(into: [:]) { counts, t in counts[t, default: 0] += 1 })
let hist = cheats.reduce(into: [:]) { counts, t in counts[t, default: 0] += 1 }
hist.keys.sorted().forEach { print("\($0) -> \(hist[$0]!)") }
print(cheats.filter { $0 >= 100 }.count)