-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay03.swift
More file actions
76 lines (62 loc) · 2.09 KB
/
Day03.swift
File metadata and controls
76 lines (62 loc) · 2.09 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
74
75
76
import AOCCore
import Foundation
struct Day03: Day {
let title = "Lobby"
var rawInput: String?
func part1() throws -> Int {
input().lines
.map { $0.characters.compactMap(Int.init) }
.map { line in
var index = 0
var left = 0
var right = 0
while index < line.count - 1 {
if line[index] > line[left] {
left = index
}
index += 1
}
index = left + 1
right = left + 1
while index < line.count {
if line[index] > line[right] {
right = index
}
index += 1
}
return line[left] * 10 + line[right]
}
.sum
}
func part2() throws -> Int {
input().lines
.map { $0.characters.compactMap(Int.init) }
.map { line in
var digits = line
.enumerated()
.suffix(12)
.map { (value: $0.element, index: $0.offset) }
digits = digits
.enumerated()
.reduce(into: []) { acc, element in
let (x, digit) = element
let upperBound = digit.index
let lowerBound = x > 0
? acc[x - 1].index + 1
: 0
let best = (lowerBound..<upperBound)
.reversed()
.reduce(digit) { current, index in
line[index] >= current.value
? (line[index], index)
: current
}
acc.append(best)
}
return digits
.map(\.value)
.reduce(0) { $0 * 10 + $1 }
}
.sum
}
}