-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day02_1.swift
executable file
·74 lines (63 loc) · 1.6 KB
/
Day02_1.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
import Foundation
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
reduce(into: .zero, +=)
}
}
extension String {
var isNotEmpty: Bool { !isEmpty }
}
func solve(for input: String) -> UInt {
enum CubeColor: String, Hashable {
case red, green, blue
}
var posibleGameIDs = [UInt]()
let maxReds: UInt = 12
let maxGreens: UInt = 13
let maxBlues: UInt = 14
let regex = #/(?:\bGame (?<id>\d+)\b:)?((?<game>.+?)(?:;|$))/#
for line in input.components(separatedBy: .newlines) {
let result = try! regex.wholeMatch(in: line)
let gameID = UInt(result!.id!)!
var isGamePosible = true
let rawSets = result!.game.components(separatedBy: ";")
for rawSet in rawSets {
let rawCubes = rawSet.components(separatedBy: ",")
for rawCube in rawCubes {
let rawCubeComponents = rawCube.components(separatedBy: " ")
.filter(\.isNotEmpty)
let cubeCount = UInt(rawCubeComponents.first!)!
let cubeColor = CubeColor(rawValue: rawCubeComponents.last!)!
switch cubeColor {
case .red:
if cubeCount > maxReds {
isGamePosible = false
break
}
case .green:
if cubeCount > maxGreens {
isGamePosible = false
break
}
case .blue:
if cubeCount > maxBlues {
isGamePosible = false
break
}
}
}
}
guard isGamePosible else { continue }
posibleGameIDs.append(gameID)
}
return posibleGameIDs.sum()
}
do {
let text = try String(
contentsOf: URL(fileURLWithPath: "Inputs/day02.txt"),
encoding: .utf8
)
print(solve(for: text))
} catch {
print("Error reading file: \(error)")
}