generated from swiftlang/swift-aoc-starter-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Y2023Day09.swift
55 lines (46 loc) · 1.68 KB
/
Y2023Day09.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
struct Y2023Day09: AdventDay {
var data: String
var regex: Regex<(Substring, Substring)> { /(-?\d+)/ }
var lines: [[Int]] {
get {
data
.components(separatedBy: .newlines)
.compactMap { line in
line.matches(of: regex).map { try! $0.output.1.toInteger() }
}
}
}
func part1() -> Any {
lines
.map { line in
var diffSequence = [line]
var containsNonZeros = true
while containsNonZeros {
let diff = zip(diffSequence.last!, diffSequence.last!.dropFirst()).map { $1 - $0 }
diffSequence.append(diff)
containsNonZeros = diff.contains(where: { $0 != 0 })
}
return diffSequence
.compactMap { $0.last }.sum
}
.sum
}
func part2() -> Any {
lines
.map { line in
var diffSequence = [line]
var containsNonZeros = true
while containsNonZeros {
let diff = zip(diffSequence.last!, diffSequence.last!.dropFirst()).map { $1 - $0 }
diffSequence.append(diff)
containsNonZeros = diff.contains(where: { $0 != 0 })
}
return diffSequence
.compactMap { $0.first }
.reversed()
.dropFirst()
.reduce(into: 0) { $0 = $1 - $0 }
}
.sum
}
}