|
| 1 | +import ArgumentParser |
| 2 | +import Foundation |
| 3 | + |
| 4 | +extension String { |
| 5 | + var length: Int { |
| 6 | + return count |
| 7 | + } |
| 8 | + |
| 9 | + subscript (i: Int) -> String { |
| 10 | + return self[i ..< i + 1] |
| 11 | + } |
| 12 | + |
| 13 | + subscript (r: Range<Int>) -> String { |
| 14 | + let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), |
| 15 | + upper: min(length, max(0, r.upperBound)))) |
| 16 | + let start = index(startIndex, offsetBy: range.lowerBound) |
| 17 | + let end = index(start, offsetBy: range.upperBound - range.lowerBound) |
| 18 | + return String(self[start ..< end]) |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +@main |
| 23 | +struct Day08: ParsableCommand { |
| 24 | + @Option(help: "Specify the input") |
| 25 | + public var input: String |
| 26 | + |
| 27 | + public func run() throws { |
| 28 | + guard let filecontent = try? String(contentsOfFile: input, encoding: .utf8) |
| 29 | + else { |
| 30 | + print("Failed to open file \(input)") |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + let lines = filecontent.components(separatedBy: .newlines) |
| 35 | + let instructions = lines[0] |
| 36 | + |
| 37 | + var map = [String: [String]]() |
| 38 | + lines.dropFirst(2).forEach { line in |
| 39 | + let parts = line.components(separatedBy: "=") |
| 40 | + let key = parts[0].trimmingCharacters(in: .whitespacesAndNewlines) |
| 41 | + let trimmed = parts[1][2..<parts[1].length-1] |
| 42 | + let value = trimmed.components(separatedBy: ", ") |
| 43 | + map[key] = value |
| 44 | + } |
| 45 | + |
| 46 | + var steps = 0 |
| 47 | + var current = "AAA" |
| 48 | + var i = 0 |
| 49 | + print(current) |
| 50 | + while current != "ZZZ" { |
| 51 | + let instruction = instructions[i] |
| 52 | + let step = map[current]! |
| 53 | + if instruction == "L" { |
| 54 | + current = step[0] |
| 55 | + } else { |
| 56 | + current = step[1] |
| 57 | + } |
| 58 | + print(current) |
| 59 | + steps += 1 |
| 60 | + i += 1 |
| 61 | + if i == instructions.length { |
| 62 | + i = 0 |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + print(steps) |
| 67 | + } |
| 68 | +} |
0 commit comments