-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay05.swift
45 lines (38 loc) · 1.32 KB
/
Day05.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import AOCCore
import Foundation
struct Day05: Day {
let title = "Print Queue"
var rawInput: String?
func part1() throws -> Int {
let rules = input().sections[0].lines.map(\.integers)
.reduce(into: [:]) { result, value in
result[value[0], default: []].append(value[1])
}
return input().sections[1].lines.map(\.integers)
.filter { update in
zip(update, update.dropFirst()).allSatisfy { lhs, rhs in
isLower(lhs, rhs, rules)
}
}
.map { $0[$0.count / 2] }
.sum
}
func part2() throws -> Int {
let rules = input().sections[0].lines.map(\.integers)
.reduce(into: [:]) { result, value in
result[value[0], default: []].append(value[1])
}
return input().sections[1].lines.map(\.integers)
.filter { update in
!zip(update, update.dropFirst()).allSatisfy { lhs, rhs in
isLower(lhs, rhs, rules)
}
}
.map { $0.sorted { isLower($0, $1, rules) } }
.map { $0[$0.count / 2] }
.sum
}
private func isLower(_ lhs: Int, _ rhs: Int, _ rules: [Int: [Int]]) -> Bool {
rules[lhs, default: []].contains(rhs)
}
}