-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path19.swift
216 lines (188 loc) · 6.38 KB
/
19.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
typealias Workflows = [String: Workflow]
typealias Workflow = [Rule]
enum Attribute: String { case x, m, a, s }
enum Op { case lt, gt }
struct Condition {
let attribute: Attribute
let op: Op
let num: Int
func isValid(part: Part) -> Bool {
switch attribute {
case .x: isValid(part.x)
case .m: isValid(part.m)
case .a: isValid(part.a)
case .s: isValid(part.s)
}
}
private func isValid(_ x: Int) -> Bool {
switch op {
case .lt: x < num
case .gt: x > num
}
}
var validRange: ClosedRange<Int> {
switch op {
case .lt: 1...(num - 1)
case .gt: (num + 1)...4000
}
}
}
struct Rule {
let condition: Condition?
let action: Action
}
enum Action {
case accept, reject
case send(String)
}
struct Part {
let x, m, a, s: Int
}
func readInput() -> (Workflows, [Part]) {
var workflows: Workflows = [:]
var parts: [Part]?
while let line = readLine() {
if line == "" {
parts = readParts()
} else {
let (name, workflow) = parseWorkflow(line)
workflows[name] = workflow
}
}
return (workflows, parts!)
}
func parseWorkflow(_ line: String) -> (name: String, workflow: Workflow) {
let splits = line.split { "{},".contains($0) }
let name = String(splits[0])
var workflow: Workflow = []
for s in splits.dropFirst(1) {
workflow.append(parseRule(s))
}
return (name: name, workflow: workflow)
}
func parseRule<S: StringProtocol>(_ s: S) -> Rule {
let sp = s.split(separator: ":")
if sp.count == 2 {
return Rule(condition: parseCondition(sp[0]), action: parseAction(sp[1]))
} else {
return Rule(condition: nil, action: parseAction(sp[0]))
}
}
func parseCondition<S: StringProtocol>(_ s: S) -> Condition {
var splits = s.split(separator: "<")
var op: Op
if splits.count > 1 {
op = .lt
} else {
splits = s.split(separator: ">")
op = .gt
}
let attribute = Attribute(rawValue: String(splits[0]))!
let num = Int(splits[1])!
return Condition(attribute: attribute, op: op, num: num)
}
func parseAction<S: StringProtocol>(_ s: S) -> Action {
switch s {
case "A": return .accept
case "R": return .reject
default: return .send(String(s))
}
}
func readParts() -> [Part] {
var parts: [Part] = []
while let line = readLine() {
let n = line.split { !$0.isNumber }.map { Int($0)! }
parts.append(Part(x: n[0], m: n[1], a: n[2], s: n[3]))
}
return parts
}
func process(workflows: Workflows, parts: [Part]) -> Int {
parts
.filter { p in isAccepted(workflows: workflows, part: p) }
.map { p in p.x + p.m + p.a + p.s }
.reduce(0, +)
}
func isAccepted(workflows: Workflows, part: Part) -> Bool {
var workflow = "in"
next: while true {
for rule in workflows[workflow]! {
if let condition = rule.condition, !condition.isValid(part: part) {
} else {
switch rule.action {
case .accept: return true
case .reject: return false
case .send(let newWorkflow):
workflow = newWorkflow
continue next
}
}
}
}
}
func filterRanges(workflows: Workflows) -> Int {
func combinations(_ attributeRanges: [Attribute: ClosedRange<Int>]) -> Int {
attributeRanges.values.reduce(1, { $0 * $1.count })
}
let attributes: [Attribute] = [.x, .m, .a, .s]
let attributeRanges =
Dictionary(uniqueKeysWithValues: attributes.map { ($0, 1...4000) })
var pending = [("in", attributeRanges)]
var acceptedCount = 0
nextPending: while let (workflow, attributeRanges) = pending.popLast() {
var attributeRanges = attributeRanges
for rule in workflows[workflow]! {
if let condition = rule.condition {
// Conditional rule, will cause attributeRanges to split.
// Find the range to which this rule applies.
let attribute = condition.attribute
let validRange = condition.validRange
let range = attributeRanges[attribute]!
let newRange = range.clamped(to: validRange)
// Create a new set of attribute ranges with this range, and
// apply the rule's action to it.
var newAttributeRanges = attributeRanges
newAttributeRanges[attribute] = newRange
switch rule.action {
case .reject:
break
case .accept:
acceptedCount += combinations(newAttributeRanges)
case .send(let newWorkflow):
pending.append((newWorkflow, newAttributeRanges))
}
// There will be a leftover range, possibly empty. Continue
// processing it if it is not empty.
//
// Because of how the problem is structured, either the leftover
// range will be of values lower than the valid range, or of
// values above the valid range, but it won't span both.
if range.lowerBound < validRange.lowerBound {
attributeRanges[attribute] =
range.lowerBound...(validRange.lowerBound - 1)
} else if validRange.upperBound < range.upperBound {
attributeRanges[attribute] =
(validRange.upperBound + 1)...range.upperBound
} else {
continue nextPending
}
} else {
// Unconditional rule, always a match, so consumes the whole.
// ranges
switch rule.action {
case .reject:
break
case .accept:
acceptedCount += combinations(attributeRanges)
case .send(let newWorkflow):
pending.append((newWorkflow, attributeRanges))
}
continue nextPending
}
}
}
return acceptedCount
}
let (workflows, parts) = readInput()
let p1 = process(workflows: workflows, parts: parts)
let p2 = filterRanges(workflows: workflows)
print(p1, p2)