Skip to content

Commit c89da6f

Browse files
committed
Day 11
1 parent 4e86796 commit c89da6f

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

Sources/AdventOfCode.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ extension ParsingCommand {
7878
Day7.self,
7979
Day8.self,
8080
Day9.self,
81-
Day10.self
81+
Day10.self,
82+
Day11.self
8283
]
8384
)
8485

Sources/Day11.swift

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

Comments
 (0)