-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay07.swift
52 lines (41 loc) · 1.47 KB
/
Day07.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
import AOCCore
import Foundation
struct Day07: Day {
let title = "Bridge Repair"
var rawInput: String?
func part1() throws -> Int {
let equations = input().lines.map(\.integers)
let operators = [
{ (a: Int, b: Int) -> Int in return a + b },
{ (a: Int, b: Int) -> Int in return a * b }
]
return equations
.filter { hasSolution(operators, $0[0], $0[1], $0.dropFirst(2)) }
.map { $0[0] }
.sum
}
func part2() throws -> Int {
let equations = input().lines.map(\.integers)
let operators = [
{ (a: Int, b: Int) -> Int in return a + b },
{ (a: Int, b: Int) -> Int in return a * b },
{ (a: Int, b: Int) -> Int in return Int("\(a)\(b)")! }
]
return equations
.filter { hasSolution(operators, $0[0], $0[1], $0.dropFirst(2)) }
.map { $0[0] }
.sum
}
private func hasSolution(_ operators: [(Int, Int) -> Int], _ target: Int, _ partialResult: Int, _ remainingValues: ArraySlice<Int>) -> Bool {
guard
partialResult <= target,
!remainingValues.isEmpty
else { return partialResult == target }
guard
let firstValue = remainingValues.first
else { return false }
return operators.contains {
hasSolution(operators, target, $0(partialResult, firstValue), remainingValues.dropFirst())
}
}
}