|
| 1 | +import ArgumentParser |
| 2 | +import Parsing |
| 3 | +import _math |
| 4 | + |
| 5 | +struct Day11: ParsingCommand { |
| 6 | + @Argument var file: String = "11.txt" |
| 7 | + |
| 8 | + static var parser: some Parser<Substring.UTF8View, [Int]> { |
| 9 | + Many { Int.parser(of: Substring.UTF8View.self) } |
| 10 | + separator: { Whitespace() } |
| 11 | + terminator: { |
| 12 | + Whitespace() |
| 13 | + End() |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + func run() throws { |
| 18 | + let input = try parsed(file: file).reduce(into: [Int:Int]()) { partialResult, i in |
| 19 | + partialResult[i, default: 0] += 1 |
| 20 | + } |
| 21 | + |
| 22 | + func iteration(partialResult: inout [Int: Int], i: (key: Int, value: Int)) { |
| 23 | + if i.key == 0 { partialResult[1, default: 0] += i.value } |
| 24 | + else if i.key.digits % 2 == 0 { |
| 25 | + let (l, r) = i.key.split |
| 26 | + partialResult[l, default: 0] += i.value |
| 27 | + partialResult[r, default: 0] += i.value |
| 28 | + } else { |
| 29 | + partialResult[i.key * 2024, default: 0] += i.value |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + let part1 = (0..<25).reduce(into: input) { input, _ in |
| 34 | + input = input.reduce(into: [Int:Int](), iteration) |
| 35 | + } |
| 36 | + |
| 37 | + print("Part 1", part1.map(\.value).reduce(0, +)) |
| 38 | + |
| 39 | + |
| 40 | + let part2 = (25..<75).reduce(into: part1) { input, i in |
| 41 | + input = input.reduce(into: [Int:Int](), iteration) |
| 42 | + } |
| 43 | + |
| 44 | + print("Part 2", part2.map(\.value).reduce(0, +)) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +fileprivate extension Int { |
| 49 | + var digits: Int { |
| 50 | + return Int(log10(Double(self + 1)).rounded(.awayFromZero)) |
| 51 | + } |
| 52 | + |
| 53 | + var split: (Int, Int) { |
| 54 | + let digits = self.digits |
| 55 | + let factor = Int(pow(10, Double(digits / 2)).rounded()) |
| 56 | + let left = self / factor |
| 57 | + let right = self % factor |
| 58 | + return (left, right) |
| 59 | + } |
| 60 | +} |
0 commit comments