-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay07.swift
77 lines (58 loc) · 1.74 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
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
import Foundation
import Tools
final class Day07Solver: DaySolver {
let dayNumber: Int = 7
struct Input {
let program: [Int]
}
func solvePart1(withInput input: Input) -> Int {
let intcode = IntcodeProcessor()
let permutations = [0, 1, 2, 3, 4].permutations
var maxThrusterSignal = 0
for permutation in permutations {
var currentInput = 0
for phaseSetting in permutation {
currentInput = intcode.executeProgram(input.program, input: [phaseSetting, currentInput]).output.last!
}
maxThrusterSignal = max(maxThrusterSignal, currentInput)
}
return maxThrusterSignal
}
func solvePart2(withInput input: Input) -> Int {
let permutations = [5, 6, 7, 8, 9].permutations
var maxThrusterSignal = 0
for permutation in permutations {
let amplifiers: [IntcodeProcessor] = [
IntcodeProcessor(),
IntcodeProcessor(),
IntcodeProcessor(),
IntcodeProcessor(),
IntcodeProcessor(),
]
var currentInput = 0
var iteration = 0
iterationLoop: while true {
for (amplifierIndex, phaseSetting) in permutation.enumerated() {
if iteration == 0 {
guard let newCurrentInput = amplifiers[amplifierIndex].executeProgramTillOutput(input.program, input: [phaseSetting, currentInput]) else {
fatalError()
}
currentInput = newCurrentInput
} else {
if let newCurrentInput = amplifiers[amplifierIndex].continueProgramTillOutput(input: [currentInput]) {
currentInput = newCurrentInput
} else {
break iterationLoop
}
}
maxThrusterSignal = max(maxThrusterSignal, currentInput)
}
iteration += 1
}
}
return maxThrusterSignal
}
func parseInput(rawString: String) -> Input {
return .init(program: rawString.parseCommaSeparatedInts())
}
}