-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay06.swift
More file actions
63 lines (51 loc) · 1.65 KB
/
Day06.swift
File metadata and controls
63 lines (51 loc) · 1.65 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
import AOCCore
import Foundation
struct Day06: Day {
let title = "Trash Compactor"
var rawInput: String?
func part1() throws -> Int {
input().lines
.map { $0.raw.split(separator: .whitespace).map(String.init) }
.columns
.map { (numbers: $0.dropLast().compactMap(Int.init), operation: $0.suffix(1).first) }
.map { numbers, operation in
if operation == "*" {
return numbers.reduce(1, *)
}
if operation == "+" {
return numbers.reduce(0, +)
}
return 0
}
.sum
}
func part2() throws -> Int {
let board = input().lines.map(\.characters)
let maxLength = board.reduce(0) { result, line in
max(result, line.count)
}
let numbers = (0..<maxLength)
.map { x in
board.reduce(0) { number, line in
guard
x < line.count,
let digit = line[x].wholeNumberValue
else { return number }
return number * 10 + digit
}
}
.split(separator: 0)
let operations = board.last?.filter { !$0.isWhitespace } ?? []
return zip(numbers, operations)
.map { numbers, operation in
if operation == "*" {
return numbers.reduce(1, *)
}
if operation == "+" {
return numbers.reduce(0, +)
}
return 0
}
.sum
}
}