-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution_2019_07.swift
81 lines (64 loc) · 2.29 KB
/
Solution_2019_07.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
75
76
77
78
79
80
81
import Foundation
struct Solution_2019_07: Solution {
var input: Input
func run() throws {
let values = try input.get()
.split(separator: ",")
.compactMap({ Int($0) })
// ------- Part 1 -------
func generatePermutations(for array: [Int]) -> [[Int]] {
var permutation = array
var result = [[Int]]()
func heapPermutation(count: Int) {
if count == 1 {
result.append(permutation)
return
}
for i in 0..<count {
heapPermutation(count: count - 1)
if count % 2 == 1 {
permutation.swapAt(0, count - 1)
} else {
permutation.swapAt(i, count - 1)
}
}
}
heapPermutation(count: array.count)
return result
}
func run(program: [Int], phases: [Int], feedbackMode: Bool = false) -> Int {
var result: Int?
let intcodes = phases
.map { Intcode(program: program, input: $0) }
intcodes[0].send(input: 0)
let last = intcodes.count - 1
intcodes[0..<last]
.enumerated()
.forEach { index, intcode in
intcode.output = { intcodes[index + 1].send(input: $0) }
}
intcodes[last].output = {
if feedbackMode {
intcodes[0].send(input: $0)
}
result = $0
}
intcodes.forEach { $0.run() }
return result!
}
let permutations = generatePermutations(for: Array(0...4))
let part1 = permutations.reduce(Int.min) { acc, x in
return max(acc, run(program: values, phases: x))
}
print(part1)
// ------- Part 2 -------
let permutations2 = generatePermutations(for: Array(5...9))
let part2 = permutations2.reduce(Int.min) { acc, x in
return max(acc, run(program: values, phases: x, feedbackMode: true))
}
print(part2)
// ------- Test -------
assert(part1 == 118936, "WA")
assert(part2 == 57660948, "WA")
}
}