-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day01_2.swift
executable file
·69 lines (63 loc) · 1.46 KB
/
Day01_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
68
69
import Foundation
extension String {
mutating func prepend(_ another: Self) {
self = "\(another)\(self)"
}
}
func solve(for input: String) -> Int {
enum RawDigit: String, CaseIterable {
case one, two, three, four, five, six, seven, eight, nine
var integerString: String {
switch self {
case .one: "1"
case .two: "2"
case .three: "3"
case .four: "4"
case .five: "5"
case .six: "6"
case .seven: "7"
case .eight: "8"
case .nine: "9"
}
}
}
func findRawDigit(
in string: some Collection<String.Element>,
saveResult: @escaping (inout String, String) -> Void
) -> String {
var formedDigit = ""
for element in string {
let char = String(element)
if Int(char) != nil {
return char
}
saveResult(&formedDigit, char)
for rawDigit in RawDigit.allCases {
if formedDigit.contains(rawDigit.rawValue) {
return rawDigit.integerString
}
}
}
fatalError("Imposible")
}
return input.components(separatedBy: .newlines)
.map { line -> Int in
let firstRawDigit = findRawDigit(in: line) { result, element in
result.append(element)
}
let lastRawDigit = findRawDigit(in: line.reversed()) { result, element in
result.prepend(element)
}
return Int(firstRawDigit + lastRawDigit)!
}
.reduce(into: 0, +=)
}
do {
let text = try String(
contentsOf: URL(fileURLWithPath: "Inputs/day01.txt"),
encoding: .utf8
)
print(solve(for: text))
} catch {
print("Error reading file: \(error)")
}