-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay05.swift
More file actions
49 lines (43 loc) · 1.32 KB
/
Day05.swift
File metadata and controls
49 lines (43 loc) · 1.32 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
import AOCCore
import Foundation
struct Day05: Day {
let title = "Cafeteria"
var rawInput: String?
func part1() throws -> Int {
let ranges = input().sections[0].lines
.map(\.integers)
.map { $0[0]...$0[1] }
let ingredients = input().sections[1].lines
.flatMap(\.integers)
return ingredients
.filter { id in
for range in ranges where range.contains(id) {
return true
}
return false
}
.count
}
func part2() throws -> Int {
input().sections[0].lines
.map(\.integers)
.map { $0[0]...$0[1] }
.sorted { $0.lowerBound < $1.lowerBound }
.reduce(into: [ClosedRange<Int>]()) { result, range in
guard
let last = result.last
else {
result.append(range)
return
}
if last.overlaps(range) {
result.removeLast()
result.append(last.lowerBound...max(last.upperBound, range.upperBound))
} else {
result.append(range)
}
}
.map { $0.upperBound - $0.lowerBound + 1 }
.sum
}
}