From ea1c1cd4625724b9eb832f1d52235ca8c5e0bbc1 Mon Sep 17 00:00:00 2001 From: Dory Date: Sun, 15 Dec 2024 21:09:15 -0800 Subject: [PATCH] Readability improvements --- day14/d14p2.swift | 4 +++- day15/d15p2.swift | 33 +++++++++++++++++---------------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/day14/d14p2.swift b/day14/d14p2.swift index fe54950..792e75b 100644 --- a/day14/d14p2.swift +++ b/day14/d14p2.swift @@ -55,7 +55,9 @@ func printRobots(_ bots: [Robot]) -> String { 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]) diff --git a/day15/d15p2.swift b/day15/d15p2.swift index 4cff6d9..a004276 100644 --- a/day15/d15p2.swift +++ b/day15/d15p2.swift @@ -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 = [] - var nexts: Set = [bot.move(dir)] - while !nexts.isEmpty { - let next = nexts.removeFirst() + var boxesToPush: Set = [] + var dests: Set = [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) } }