-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution_2020_20.swift
413 lines (386 loc) · 15.1 KB
/
Solution_2020_20.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//
// Solution_2020_20.swift
//
//
// Created by Ivan Chalov on 20.12.20.
//
import Foundation
import Algorithms
import Prelude
private struct Tile: CustomDebugStringConvertible {
var tileId: Int
var content: [[Character]]
var debugDescription: String {
var debugString = "Tile \(tileId):\n"
for row in content {
debugString += "\(String(row))\n"
}
return debugString
}
var clockwiseFromTopPossibleEdges: [[[Character]]] {
[
[
content.first!,
content.first!.reversed(),
],
[
content[column: 9],
content[column: 9].reversed(),
],
[
content.last!,
content.last!.reversed(),
],
[
content[column: 0],
content[column: 0].reversed(),
],
]
}
var possibleEdges: FlattenSequence<[[[Character]]]> {
clockwiseFromTopPossibleEdges.joined()
}
mutating func rotate(times: Int) {
self.content.rotate(times: times)
}
mutating func hflip() {
self.content .hflip()
}
mutating func vflip() {
self.content.vflip()
}
var insides: [[Character]] {
self.content.dropFirst().dropLast().map { $0.dropFirst().dropLast() }
}
}
private extension Array where Element == Array<Character> {
mutating func rotate(times: Int) {
let times = times % 4
if times == 0 { return }
if times == 1 { self = self.indices.map { self[column: $0] }; self.hflip() }
if times == 2 { self.vflip(); self.hflip() }
if times == 3 { self.rotate(times: 1); self.rotate(times: 2) }
}
mutating func hflip() {
self = self.map { $0.reversed() }
}
mutating func vflip() {
self = self.reversed()
}
}
extension Tile {
init(string: String) {
let (tileId, content) = string
.split(whereSeparator: \.isNewline)
.map(String.init)
|> { (rows: [String]) -> (Int, [[Character]]) in
(
Int(rows[0].dropFirst(5).dropLast())!,
rows.dropFirst().map { $0.map(id) }
)
}
self.init(tileId: tileId, content: content)
}
}
struct Solution_2020_20: Solution {
var input: Input
func run() throws {
let input = try self.input.get()
.components(separatedBy: "\n\n")
.map(Tile.init(string:))
let tiles = Dictionary(uniqueKeysWithValues: input.map { ($0.tileId, $0) })
// ------- Part 1 -------
let possibleEdges = input
.flatMap { tile -> [(String, Int)] in
tile.possibleEdges.map { (String($0), tile.tileId) }
}
.sorted(by: { $0.0 < $1.0 })
var matchedEdges = [Int: Int]()
var index = 0
while index < possibleEdges.count {
if possibleEdges[index].0 == possibleEdges[index + 1].0 {
matchedEdges[possibleEdges[index].1, default: 0] += 1
matchedEdges[possibleEdges[index + 1].1, default: 0] += 1
index += 2
} else {
index += 1
}
}
var corners = matchedEdges.filter { $0.value == 4 }
let part1 = corners.keys.product()
print(part1)
// ------- Part 2 -------
let startingCorner = tiles[corners.keys.first!]!
// let startingCorner = tiles[2801]!
corners.removeValue(forKey: startingCorner.tileId)
var outerEdges = matchedEdges.filter { $0.value == 6 }
var innerTiles = matchedEdges.filter { $0.value == 8 }
var puzzle = [[Tile]]()
// gathering the first row
puzzle.append([startingCorner])
var currentRow = 0
var currentColumn = 1
var previousTile = startingCorner
while currentColumn != 11 {
for tileId in Set(outerEdges.keys) {
let tile = tiles[tileId]!
if Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2 {
currentColumn += 1
puzzle[currentRow].append(tile)
previousTile = tile
outerEdges.removeValue(forKey: tileId)
break
}
}
}
for tileId in Set(corners.keys) {
let tile = tiles[tileId]!
if Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2 {
currentColumn = 0
puzzle[currentRow].append(tile)
previousTile = puzzle[currentRow][0]
corners.removeValue(forKey: tileId)
currentRow += 1
break
}
}
// gathering rows before the last one
while currentRow != 11 {
puzzle.append([])
for tileId in Set(outerEdges.keys) {
let tile = tiles[tileId]!
if Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2 {
currentColumn += 1
puzzle[currentRow].append(tile)
previousTile = tile
outerEdges.removeValue(forKey: tileId)
break
}
}
while currentColumn != 11 {
for tileId in Set(innerTiles.keys) {
let tile = tiles[tileId]!
if
Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2,
Set(tile.possibleEdges).intersection(Set(puzzle[currentRow - 1][currentColumn].possibleEdges)).count == 2
{
currentColumn += 1
puzzle[currentRow].append(tile)
previousTile = tile
innerTiles.removeValue(forKey: tileId)
break
}
}
}
for tileId in Set(outerEdges.keys) {
let tile = tiles[tileId]!
if
Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2,
Set(tile.possibleEdges).intersection(Set(puzzle[currentRow - 1][currentColumn].possibleEdges)).count == 2
{
puzzle[currentRow].append(tile)
previousTile = puzzle[currentRow][0]
outerEdges.removeValue(forKey: tileId)
currentColumn = 0
currentRow += 1
break
}
}
}
// gathering the last row
puzzle.append([])
for tileId in Set(corners.keys) {
let tile = tiles[tileId]!
if Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2 {
puzzle[currentRow].append(tile)
previousTile = tile
corners.removeValue(forKey: tileId)
currentColumn += 1
break
}
}
while currentColumn != 11 {
for tileId in Set(outerEdges.keys) {
let tile = tiles[tileId]!
if
Set(tile.possibleEdges).intersection(Set(previousTile.possibleEdges)).count == 2,
Set(tile.possibleEdges).intersection(Set(puzzle[currentRow - 1][currentColumn].possibleEdges)).count == 2
{
currentColumn += 1
puzzle[currentRow].append(tile)
previousTile = tile
outerEdges.removeValue(forKey: tileId)
break
}
}
}
puzzle[currentRow].append(tiles[corners.keys.first!]!)
corners.removeValue(forKey: corners.keys.first!)
// check that all tiles were used
assert(corners.count == 0)
assert(outerEdges.count == 0)
assert(innerTiles.count == 0)
// flip and rotate the tiles to correct positions
func flipAndRotateUntilMatches(left: inout Tile, right: inout Tile, bottom: Tile) {
for (i, edges) in left.clockwiseFromTopPossibleEdges.indexed() {
for (j, otherEdges) in right.clockwiseFromTopPossibleEdges.indexed() {
if Set(edges) == Set(otherEdges) {
// if all's good, i == 1, j == 3 (right edge matches to left edge)
// so let's rotate the tiles accordingly
left.rotate(times:((1 - i) + 4) % 4)
right.rotate(times:((3 - j) + 4) % 4)
// now flipping
let updatedEdges = left.clockwiseFromTopPossibleEdges[1]
let updatedOtherEdges = right.clockwiseFromTopPossibleEdges[3]
if updatedEdges[0] == updatedOtherEdges[1] {
right.vflip()
} else if updatedEdges[1] == updatedOtherEdges[0] {
left.vflip()
}
// make sure we can attach bottom tile
let bottomEdges = left.clockwiseFromTopPossibleEdges[2]
if Set(bottom.possibleEdges).intersection(Set(bottomEdges)).count == 0 {
left.vflip()
right.vflip()
}
return
}
}
}
fatalError("failed to match two tiles")
}
func flipAndRotateRightTile(left: Tile, right: inout Tile) {
let edges = left.clockwiseFromTopPossibleEdges[1]
for (j, otherEdges) in right.clockwiseFromTopPossibleEdges.indexed() {
if Set(edges) == Set(otherEdges) {
right.rotate(times:((3 - j) + 4) % 4)
if edges[0] == right.clockwiseFromTopPossibleEdges[3][1] {
right.vflip()
}
return
}
}
fatalError("failed to match two tiles")
}
func flipAndRotateBottomTile(top: Tile, bottom: inout Tile) {
let edges = top.clockwiseFromTopPossibleEdges[2]
for (j, otherEdges) in bottom.clockwiseFromTopPossibleEdges.indexed() {
if Set(edges) == Set(otherEdges) {
bottom.rotate(times:(4 - j) % 4)
if edges[0] == bottom.clockwiseFromTopPossibleEdges[0][1] {
bottom.hflip()
}
return
}
}
fatalError("failed to match two tiles")
}
// let's take care of the first row
var currentTile = puzzle[0][0]
var rightTile = puzzle[0][1]
flipAndRotateUntilMatches(left: ¤tTile, right: &rightTile, bottom: puzzle[1][0])
puzzle[0][0] = currentTile
puzzle[0][1] = rightTile
currentTile = rightTile
rightTile = puzzle[0][2]
for i in 2...11 {
flipAndRotateRightTile(left: currentTile, right: &rightTile)
puzzle[0][i] = rightTile
currentTile = rightTile
if i < 11 {
rightTile = puzzle[0][i + 1]
}
}
// now we can do the other rows
currentRow = 1
while currentRow != 12 {
currentTile = puzzle[currentRow - 1][0]
var bottomTile = puzzle[currentRow][0]
flipAndRotateBottomTile(top: currentTile, bottom: &bottomTile)
puzzle[currentRow][0] = bottomTile
currentTile = bottomTile
rightTile = puzzle[currentRow][1]
for i in 1...11 {
flipAndRotateRightTile(left: currentTile, right: &rightTile)
puzzle[currentRow][i] = rightTile
currentTile = rightTile
if i < 11 {
rightTile = puzzle[currentRow][i + 1]
}
}
currentRow += 1
}
// cool... now to creating the actual picture
let finalSize = 12 * (10 - 2)
var image = Array(repeating: Array(repeating: Character("."), count: finalSize), count: finalSize)
var i = 0
var j = 0
for (rowNumber, row) in puzzle.indexed() {
for (tileColumn, tile) in row.indexed() {
i = 8 * rowNumber
for xs in tile.insides {
j = 8 * tileColumn
for y in xs {
image[i][j] = y
j += 1
}
i += 1
}
}
}
let seaMonster = """
..................#.
#....##....##....###
.#..#..#..#..#..#...
""".split(whereSeparator: \.isNewline).map { $0.map(id) }
func countMonsters(image: [[Character]]) -> Int {
var monsters = 0
image.slidingWindows(ofCount: seaMonster.count).forEach { window in
let slices = window.map { $0.slidingWindows(ofCount: seaMonster[0].count) }
var i1 = slices[0].makeIterator()
var i2 = slices[1].makeIterator()
var i3 = slices[2].makeIterator()
while let row1 = i1.next(), let row2 = i2.next(), let row3 = i3.next() {
var foundIt = true
loopOverWindow: for (i, row) in [row1, row2, row3].indexed() {
for (j, char) in row.indexed() {
if seaMonster[i][j - row.startIndex] == "#" && char != "#" {
foundIt = false
break loopOverWindow
}
}
}
monsters += foundIt ? 1 : 0
}
}
return monsters
}
func findRotation(image: [[Character]]) -> Int {
var image = image
var monstersNumber = countMonsters(image: image)
if monstersNumber != 0 { return monstersNumber }
for i in (1...3) {
image.rotate(times: i)
monstersNumber = countMonsters(image: image)
if monstersNumber != 0 { return monstersNumber }
}
image.hflip()
monstersNumber = countMonsters(image: image)
if monstersNumber != 0 { return monstersNumber }
for i in (1...3) {
image.rotate(times: i)
monstersNumber = countMonsters(image: image)
if monstersNumber != 0 { return monstersNumber }
}
fatalError("Couldn't find monsters")
}
let monstersNumber = findRotation(image: image)
let seaMonsterPixels = seaMonster.map { $0.filter { $0 == "#" }.count }.sum()
let totalPixels = image.map { $0.filter { $0 == "#" }.count }.sum()
let part2 = totalPixels - monstersNumber * seaMonsterPixels
print(part2)
// ------- Test -------
assert(part1 == 51214443014783, "WA")
assert(part2 == 2065, "WA")
}
}