-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution_2018_03.swift
81 lines (66 loc) · 2.07 KB
/
Solution_2018_03.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
import Foundation
private struct Point: Hashable {
let x: Int
let y: Int
}
private struct Patch {
let id: String
let x: Int
let y: Int
let width: Int
let height: Int
let points: [Point]
init(id: String, x: Int, y: Int, width: Int, height: Int) {
self.id = id
self.x = x
self.y = y
self.width = width
self.height = height
self.points = (x ..< x + width).flatMap { x0 in
(y ..< y + height).map { y0 in
return Point(x: x0, y: y0)
}
}
}
}
extension Patch {
init(patchDescription: String) {
let pattern = "#(?<id>\\d+) @ (?<x>\\d+),(?<y>\\d+): (?<width>\\d+)x(?<height>\\d+)"
let regex = try! NSRegularExpression(pattern: pattern)
let captureGroupToString = regex.captureGroupToString(in: patchDescription)
let captureGroupToInt = regex.captureGroupToInt(in: patchDescription)
guard
let id = captureGroupToString("id"),
let x = captureGroupToInt("x"),
let y = captureGroupToInt("y"),
let width = captureGroupToInt("width"),
let height = captureGroupToInt("height")
else {
fatalError("Wrong input format")
}
self.init(id: id, x: x, y: y, width: width, height: height)
}
}
struct Solution_2018_03: Solution {
var input: Input
func run() throws {
let patches = try input.get()
.components(separatedBy: .newlines)
.map({ Patch(patchDescription: $0) })
let points = patches.flatMap({ $0.points })
let setOfPoints = NSCountedSet(array: points)
let part1 = setOfPoints.filter({
setOfPoints.count(for: $0) > 1
}).count
print(part1)
let part2 = patches.first(where: { patch in
patch.points.allSatisfy{ point in
setOfPoints.count(for: point) == 1
}
})!.id
print(part2)
// ------- Test -------
assert(part1 == 111630, "WA")
assert(part2 == "724", "WA")
}
}