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

@@ -55,7 +55,9 @@ func printRobots(_ bots: [Robot]) -> String {
screen[q][bot.x] = "" screen[q][bot.x] = ""
} }
} }
return screen.map { row in row.joined() }.joined(separator: "\n") return "" + String(repeating: "", count: w) + "\n" +
screen.map { row in "" + row.joined() + "" }.joined(separator: "\n") +
"\n" + String(repeating: "", count: w) + ""
} }
var bots = try readInput(CommandLine.arguments[1]) var bots = try readInput(CommandLine.arguments[1])

View File

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