-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDay16.swift
280 lines (230 loc) · 6.38 KB
/
Day16.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import Algorithms
import Collections
import Foundation
import RegexBuilder
fileprivate extension StringProtocol {
var integers: [Int] {
return self
.split{ "-0123456789".contains($0) == false }
.map { Int($0)! }
}
}
func + <T>(el: T, arr: [T]) -> [T] {
var ret = arr
ret.insert(el, at: 0)
return ret
}
func cartesianProduct<T>(_ arrays: [[T]]) -> [[T]] {
guard let head = arrays.first else {
return []
}
let first = Array(head)
func pel(
_ el: T,
_ ll: [[T]],
_ a: [[T]] = []
) -> [[T]] {
switch ll.count {
case 0:
return a.reversed()
case _:
let tail = Array(ll.dropFirst())
let head = ll.first!
return pel(el, tail, el + head + a)
}
}
return arrays.reversed()
.reduce([first], {res, el in el.flatMap({ pel($0, res) }) })
.map({ $0.dropLast(first.count) })
}
struct Valve: Hashable {
var name: String
var flowRate: Int
var destinations: [String]
}
struct Path: Hashable {
var currentPosition: Valve
var timestamp: Int
var valves: [Valve: Int]
var score: Int {
valves.reduce(into: 0) { score, tuple in
score += tuple.key.flowRate * (30 - tuple.value)
}
}
}
struct Route: Hashable {
var valve: Valve
var timestamp: Int
}
struct Path2: Hashable {
var currentPositions: [Route]
var valves: [Valve: Int]
var score: Int {
valves.reduce(into: 0) { score, tuple in
score += tuple.key.flowRate * (26 - tuple.value)
}
}
}
struct Day16: Day {
var input: String
init(input: String) {
self.input = input
}
func partOne() -> String {
let valves = input
.split(separator: "\n")
.map { parseLine(String($0)) }
.reduce(into: [String: Valve]()) { dict, tuple in
dict[tuple.0] = tuple.1
}
let shortestPaths = generateShortestPaths(from: valves)
let starting = Path(
currentPosition: valves["AA"]!,
timestamp: 0,
valves: [:]
)
struct Visit: Hashable {
var current: String
var valves: Set<String>
}
var visited: [Visit: (score: Int, timestamp: Int)] = [:]
var paths: [Int: Set<Path>] = [0 : [starting]]
var maxScore = 0
while let score = paths.keys.max() {
guard let path = paths[score]?.popFirst() else {
paths.removeValue(forKey: score)
continue
}
paths[score]?.remove(path)
let visit = Visit(
current: path.currentPosition.name,
valves: Set(path.valves.keys.map(\.name))
)
if let existing = visited[visit] {
if existing.score > path.score {
continue
} else if existing.score == path.score {
if existing.timestamp < path.timestamp {
continue
}
}
}
visited[visit] = (path.score, path.timestamp)
for (nextValve, steps) in shortestPaths[path.currentPosition]! {
if path.valves.keys.contains(nextValve) { continue }
if nextValve.flowRate == 0 { continue }
if path.timestamp + steps + 1 > 30 { continue }
var newPath = path
newPath.currentPosition = nextValve
newPath.timestamp += steps + 1
newPath.valves[nextValve] = newPath.timestamp
maxScore = max(maxScore, newPath.score)
paths[newPath.score, default: []].insert(newPath)
}
}
return maxScore.description
}
func partTwo() -> String {
let valves = input
.split(separator: "\n")
.map { parseLine(String($0)) }
.reduce(into: [String: Valve]()) { dict, tuple in
dict[tuple.0] = tuple.1
}
let shortestPaths = generateShortestPaths(from: valves)
let starting = Path2(
currentPositions: [
Route(valve: valves["AA"]!, timestamp: 0),
Route(valve: valves["AA"]!, timestamp: 0)
],
valves: [:]
)
struct Visit: Hashable {
var current: Set<Route>
var valves: Set<String>
}
var visited: [Visit: Int] = [:]
var paths: [Int: Set<Path2>] = [0 : [starting]]
var maxScore = 0 {
didSet {
if maxScore > oldValue {
print("New Max Score:", maxScore)
}
}
}
let timeLimit = 26
while let projectedScore = paths.keys.max() {
guard let path = paths[projectedScore]?.popFirst() else {
paths.removeValue(forKey: projectedScore)
continue
}
paths[projectedScore]?.remove(path)
let visit = Visit(
current: Set(path.currentPositions),
valves: Set(path.valves.keys.map(\.name))
)
if let existingScore = visited[visit], existingScore >= path.score {
continue
}
visited[visit] = path.score
let nextRoutesPerPosition = path.currentPositions
.map { route -> [Route] in
let next = shortestPaths[route.valve]!
.filter { nextValve, steps in
if path.valves.keys.contains(nextValve) { return false }
if nextValve.flowRate == 0 { return false }
if route.timestamp + steps + 1 > timeLimit { return false }
return true
}
.map { Route(valve: $0.key, timestamp: route.timestamp + $0.value + 1) }
return next.isEmpty ? [route] : next
}
for nextRoutes in cartesianProduct(nextRoutesPerPosition) {
if Set(nextRoutes.map(\.valve).map(\.name)).count != nextRoutes.count {
continue
}
if nextRoutes == path.currentPositions {
continue
}
var newPath = path
newPath.currentPositions = nextRoutes
nextRoutes.forEach { route in
newPath.valves[route.valve] = route.timestamp
}
maxScore = max(maxScore, newPath.score)
paths[newPath.score, default: []].insert(newPath)
}
}
return maxScore.description
}
func parseLine(_ line: String) -> (String, Valve) {
let name = String(line.dropFirst(6).prefix(2))
let flowRate = line.integers.first!
let destinations = line
.suffix(while: { $0.isLowercase == false })
.dropFirst()
.components(separatedBy: ", ")
return (name, Valve(name: name, flowRate: flowRate, destinations: destinations))
}
func generateShortestPaths(from valves: [String: Valve]) -> [Valve: [Valve: Int]] {
var shortestPaths: [Valve: [Valve: Int]] = [:]
for (_, valve) in valves {
var localShortestPaths: [Valve: Int] = [:]
var queue = Deque(valve.destinations.map { (valve: valves[$0]!, steps: 1) })
while let destination = queue.popFirst() {
if localShortestPaths.keys.contains(destination.valve) {
continue
}
localShortestPaths[destination.valve] = destination.steps
if localShortestPaths.count == valves.count {
break
}
for next in destination.valve.destinations.map({ valves[$0]! }) {
queue.append((next, destination.steps + 1))
}
}
shortestPaths[valve] = localShortestPaths
}
return shortestPaths
}
}