generated from swiftlang/swift-aoc-starter-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Y2023Day06.swift
43 lines (36 loc) · 1.58 KB
/
Y2023Day06.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
struct Y2023Day06: AdventDay {
var data: String
// Non-capturing group zero or more words followed by a a colon,
// proceeds with zero or more spaces,
// captures one or more digits
var regex: Regex<(Substring, Substring)> { /(?:\w*:)?\s*(\d+)/ }
func part1() -> Any {
let lines = data.components(separatedBy: .newlines)
let times = lines[0].matches(of: regex).map { try! "\($0.output.1)".toInteger() }
let distances = lines[1].matches(of: regex).map { try! "\($0.output.1)".toInteger() }
return zip(times, distances)
.map { duration, distance in
(0...duration)
.dropFirst()
.dropLast()
.filter { ($0...duration).delta * $0 > distance }.count
}
.reduce(1, *)
}
func part2() -> Any {
let lines = data.components(separatedBy: .newlines)
let maxTime = try! lines[0].matches(of: regex).map { "\($0.output.1)" }.joined().toInteger()
let distance = try! lines[1].matches(of: regex).map { "\($0.output.1)" }.joined().toInteger()
let range = (0...maxTime)
let minFirstIndex = range
.dropFirst()
.dropLast()
.firstIndex(where: { ($0...maxTime).delta * $0 > distance })!
let maxFistIndex = range
.dropFirst()
.dropLast()
.reversed()
.firstIndex(where: { ($0...maxTime).delta * $0 > distance })!
return range[maxFistIndex.base] - range[minFirstIndex]
}
}