-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution_2020_03.swift
67 lines (60 loc) · 1.77 KB
/
Solution_2020_03.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
//
// Solution_2020_03.swift
//
//
// Created by Ivan Chalov on 03.12.20.
//
import Foundation
import Algorithms
private enum Point {
case empty
case tree
init(character: Character) {
switch character {
case "#":
self = .tree
case ".":
self = .empty
default:
fatalError("Incorrect Input")
}
}
}
struct Solution_2020_03: Solution {
var input: Input
func run() throws {
let input = try self.input.get()
.split(whereSeparator: \.isNewline)
.map(String.init)
.map { $0.map(Point.init(character:)) }
// ------- Part 1 -------
func solve(steps: [(x: Int, y: Int)]) -> Int {
let width = input[0].count
return input.indices
.reduce(into: Array(repeating: 0, count: steps.count)) { acc, row in
steps.indexed()
.filter { _, step in
row % step.y == 0
}
.map { index, step in
(index: index, element: step.x * (row / step.y) % width)
}
.filter { _, column in
input[row][column] == .tree
}
.forEach { index, _ in
acc[index] += 1
}
}
.product()
}
let part1 = solve(steps: [(3,1)])
print(part1)
// ------- Part 2 -------
let part2 = solve(steps: [(1,1), (3,1), (5,1), (7,1), (1,2)])
print(part2)
// ------- Test -------
assert(part1 == 191, "WA")
assert(part2 == 1478615040, "WA")
}
}