-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay02.swift
More file actions
73 lines (66 loc) · 2.05 KB
/
Day02.swift
File metadata and controls
73 lines (66 loc) · 2.05 KB
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
import AOCCore
import Foundation
import RegexBuilder
struct Day02: Day {
let title = "Cube Conundrum"
var rawInput: String?
func part1() throws -> Int {
let limits = ["red": 12, "green": 13, "blue": 14]
return input().lines
.map { line in
line
.subsets()
.allSatisfy { subset in
limits.allSatisfy { color, maxAllowed in
subset[color, default: 0] <= maxAllowed
}
}
}
.enumerated()
.reduce(into: 0) { result, item in
if item.element {
result += item.offset + 1
}
}
}
func part2() throws -> Int {
input().lines
.map { line in
let maxValues = line
.subsets()
.reduce((red: 0, green: 0, blue: 0)) { result, subset in
(
red: max(result.red, subset["red", default: 0]),
green: max(result.green, subset["green", default: 0]),
blue: max(result.blue, subset["blue", default: 0])
)
}
return maxValues.red * maxValues.green * maxValues.blue
}
.sum
}
}
private extension Line {
func subsets() -> [[String: Int]] {
let query = Regex {
TryCapture.integer
OneOrMore(.whitespace)
TryCapture {
ChoiceOf {
"blue"
"red"
"green"
}
} transform: { String($0) }
}
return self.raw
.split(separator: ";")
.map { group in
group
.matches(of: query)
.reduce(into: [:]) { result, element in
result[element.output.2, default: 0] += element.output.1
}
}
}
}