-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay04.swift
51 lines (41 loc) · 1.63 KB
/
Day04.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
import AOCCore
import Foundation
struct Day04: Day {
let title = "Ceres Search"
var rawInput: String?
func part1() throws -> Int {
let board = input().lines.map(\.characters)
let target = Array("XMAS")
let directions = [Direction.up, .down, .left, .right, .upLeft, .upRight, .downLeft, .downRight]
return GridSequence(board)
.map { position in
directions.count { search(position, $0, 0, target, board) }
}
.sum
}
func part2() throws -> Int {
let board = input().lines.map(\.characters)
let target = Array("MAS")
let directions: [Direction: [(offset: (y: Int, x: Int), direction: Direction)]] = [
.downRight: [((y: 2, x: 0), .upRight), ((y: 0, x: 2), .downLeft)],
.upLeft: [((y: -2, x: 0), .downLeft), ((y: 0, x: -2), .upRight)]
]
return GridSequence(board)
.map { position in
directions.count { key, value in
search(position, key, 0, target, board) &&
value.contains { search(position.offset($0.offset), $0.direction, 0, target, board) }
}
}
.sum
}
private func search(_ position: Position, _ direction: Direction, _ targetIndex: Int, _ target: [Character], _ board: [[Character]]) -> Bool {
guard
board[position] == target[targetIndex]
else { return false }
guard
targetIndex < target.count - 1
else { return true }
return search(position.offset(direction), direction, targetIndex + 1, target, board)
}
}