-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay01.swift
More file actions
47 lines (40 loc) · 1.15 KB
/
Day01.swift
File metadata and controls
47 lines (40 loc) · 1.15 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
import AOCCore
import Foundation
import RegexBuilder
struct Day01: Day {
let title = "Trebuchet?!"
var rawInput: String?
func part1() throws -> Int {
let lines = input().lines.map(\.characters)
return lines
.map { line in
let left = line.first(where: \.isNumber).flatMap(Int.init) ?? 0
let right = line.last(where: \.isNumber).flatMap(Int.init) ?? 0
return left * 10 + right
}
.sum
}
func part2() throws -> Int {
let query = Regex {
Lookahead {
ChoiceOf {
TryCapture.wordInteger
TryCapture.integer
}
}
}
return input().lines
.map { line in
line.raw
.matches(of: query)
.compactMap { $0.output.1 ?? $0.output.2 }
.flatMap(\.digits)
}
.map { line in
let left = line.first ?? 0
let right = line.last ?? 0
return left * 10 + right
}
.sum
}
}