generated from swiftlang/swift-aoc-starter-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Y2023Day04.swift
74 lines (63 loc) · 2.25 KB
/
Y2023Day04.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
70
71
72
73
74
import Foundation
struct Y2023Day04: AdventDay {
let shouldLog = false
var data: String
func part1() -> Any {
cards(lines: data.components(separatedBy: .newlines))
.reduce(into: 0) { $0 += $1.point }
}
func part2() -> Any {
var sum = 0
let cards = cards(lines: data.components(separatedBy: .newlines))
var dict: [Int: [Card]] = Dictionary(grouping: cards) { $0.id }
for index in cards.indices {
for card in dict[index + 1]! {
cards[(card.id..<card.id + card.matchedNumbers.count)]
.forEach { dict[$0.id, default: []].append($0) }
}
sum += dict[index + 1]?.count ?? 0
}
return sum
}
private func cards(lines: [String]) -> [Card] {
lines
.compactMap { line -> Card? in
guard !line.isEmpty else {
return nil
}
let id = try! line.firstMatch(of: /^Card\s+(\d+):/)!.1.toInteger()
let numbers = line.drop(while: { $0 != ":" }).components(separatedBy: "|")
let winningNumbers = numbers
.first!
.components(separatedBy: .whitespaces)
.compactMap { try? $0.toInteger() }
let collectedNumbers = numbers.last!
.components(separatedBy: .whitespaces)
.compactMap { try? $0.toInteger() }
return Card(
id: id,
winningNumbers: Set(winningNumbers),
collectedNumbers: Set(collectedNumbers)
)
}
}
}
struct Card: Hashable {
var id: Int = -1
var winningNumbers: Set<Int> = []
var collectedNumbers: Set<Int> = []
var matchedNumbers: Set<Int> {
winningNumbers.intersection(collectedNumbers)
}
var point: Int {
matchedNumbers
.enumerated()
.reduce(into: 0) { partialResult, value in
if value.offset == 0 {
partialResult += 1
} else {
partialResult *= 2
}
}
}
}