-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day02_2.swift
executable file
·67 lines (57 loc) · 1.52 KB
/
Day02_2.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
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 minimumPosibleGamePowers = [UInt]()
let regex = #/(?:\bGame (?<id>\d+)\b:)?((?<game>.+?)(?:;|$))/#
for line in input.components(separatedBy: .newlines) {
let result = try! regex.wholeMatch(in: line)
var maxReds: UInt = 1
var maxGreens: UInt = 1
var maxBlues: UInt = 1
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 {
maxReds = cubeCount
}
case .green:
if cubeCount > maxGreens {
maxGreens = cubeCount
}
case .blue:
if cubeCount > maxBlues {
maxBlues = cubeCount
}
}
}
}
minimumPosibleGamePowers.append(maxReds * maxGreens * maxBlues)
}
return minimumPosibleGamePowers.sum()
}
do {
let text = try String(
contentsOf: URL(fileURLWithPath: "Inputs/day02.txt"),
encoding: .utf8
)
print(solve(for: text))
} catch {
print("Error reading file: \(error)")
}