41 lines
1.2 KiB
Swift
41 lines
1.2 KiB
Swift
import Foundation
|
|
|
|
func readInput(_ filePath: String) throws -> ([Int: Set<Int>], [[Int]]) {
|
|
let content = try String(contentsOfFile: filePath, encoding: .ascii)
|
|
var rules: [Int: Set<Int>] = [:]
|
|
var pages: [[Int]] = []
|
|
var readingRules = true
|
|
for l in content.split(separator: "\n", omittingEmptySubsequences: false) {
|
|
if l == "" {
|
|
readingRules = false
|
|
continue
|
|
}
|
|
if readingRules {
|
|
let rule = l.split(separator: "|").map { Int($0)! }
|
|
let (before, after) = (rule[0], rule[1])
|
|
let current = rules[before, default: []]
|
|
rules[before] = current.union([after])
|
|
} else {
|
|
pages.append(l.split(separator: ",").map { Int($0)! })
|
|
}
|
|
}
|
|
return (rules, pages)
|
|
}
|
|
|
|
func goodPages(_ pages: [Int], against rules: [Int: Set<Int>]) -> Bool {
|
|
var seen: Set<Int> = []
|
|
for page in pages {
|
|
if !rules[page, default: []].isDisjoint(with: seen) {
|
|
return false
|
|
}
|
|
seen.insert(page)
|
|
}
|
|
return true
|
|
}
|
|
|
|
let (rules, manuals) = try readInput(CommandLine.arguments[1])
|
|
let answer = manuals
|
|
.filter { goodPages($0, against: rules) }
|
|
.map { $0[$0.count/2] }.reduce(0, +)
|
|
print(answer)
|