Readability improvements

This commit is contained in:
2024-12-15 21:09:15 -08:00
parent 779f21a289
commit ea1c1cd462
2 changed files with 20 additions and 17 deletions

View File

@@ -16,9 +16,9 @@ enum Move: Character, CustomStringConvertible {
}
}
struct Item: Hashable, CustomStringConvertible {
struct Item: Hashable {
let (x, y): (Int, Int)
var description: String { return "(\(x), \(y))" }
var rightCell: Item { return Item(x: x+1, y: y) }
var gps: Int { return x + 100*y }
func move(_ m: Move) -> Item {
let (dx, dy) = m.delta
@@ -58,10 +58,11 @@ struct Map: CustomStringConvertible {
for (y, line) in s.enumerated() {
for (x0, char) in line.enumerated() {
let x = 2*x0
let item = Item(x: x, y: y)
switch char {
case "#": walls.formUnion([Item(x: x, y: y), Item(x: x+1, y: y)])
case "O": boxes.boxes.insert(Item(x: x, y: y))
case "@": bot = Item(x: x, y: y)
case "#": walls.formUnion([item, item.rightCell])
case "O": boxes.boxes.insert(item)
case "@": bot = item
default: ()
}
}
@@ -70,19 +71,19 @@ struct Map: CustomStringConvertible {
}
mutating func move(_ dir: Move) {
var pushes: Set<Item> = []
var nexts: Set<Item> = [bot.move(dir)]
while !nexts.isEmpty {
let next = nexts.removeFirst()
var boxesToPush: Set<Item> = []
var dests: Set<Item> = [bot.move(dir)]
while !dests.isEmpty {
let next = dests.removeFirst()
if let box = boxes.at(x: next.x, y: next.y) {
pushes.insert(box)
boxesToPush.insert(box)
let movedBox = box.move(dir)
switch dir {
case Move.w: nexts.insert(movedBox)
case Move.e: nexts.insert(Item(x: movedBox.x+1, y: movedBox.y))
case Move.w: dests.insert(movedBox)
case Move.e: dests.insert(movedBox.rightCell)
case Move.n, Move.s:
nexts.insert(movedBox)
nexts.insert(Item(x: movedBox.x+1, y: movedBox.y))
dests.insert(movedBox)
dests.insert(movedBox.rightCell)
}
continue
}
@@ -90,8 +91,8 @@ struct Map: CustomStringConvertible {
return
}
}
pushes.forEach { boxes.boxes.remove($0) }
pushes.forEach { boxes.boxes.insert($0.move(dir)) }
boxesToPush.forEach { boxes.boxes.remove($0) }
boxesToPush.forEach { boxes.boxes.insert($0.move(dir)) }
bot = bot.move(dir)
}
}