-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path20.bstate.swift
242 lines (211 loc) · 6.64 KB
/
20.bstate.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
enum Module {
case flip(String, [Int], UInt8)
case conjunction(String, [Int], [Int], UInt64)
case broadcast(String, [Int])
case other(String)
}
extension Module: CustomStringConvertible {
var description: String {
func pad2(_ n: Int) -> String {
n < 10 ? "0\(n)" : "\(n)"
}
func outs(_ outputs: [Int]) -> String {
outputs.sorted().map { pad2($0) }.joined(separator: "|")
}
switch self {
case .flip(let name, let outputs, _):
return "\(name):\(stateString!)>\(outs(outputs))"
case .conjunction(let name, _, let outputs, _):
return "\(name):\(stateString!)>\(outs(outputs))"
case .broadcast(let name, let outputs):
return "\(name):>\(outs(outputs))"
case .other(let name):
return name
}
}
var stateString: String? {
switch self {
case .conjunction(_, let ik, _, let state): _conjunctionString(ik, state)
case .flip(_, _, let state): state == 1 ? "1" : "0"
default: nil
}
}
}
func _conjunctionString(_ ik: [Int], _ state: UInt64) -> String {
var result = [Character]()
for (i, c) in Array(String(state, radix: 2)).reversed().enumerated() {
if ik.firstIndex(of: i) != nil {
result.append(c)
}
}
return String(result)
}
var modulesIndexToName: [Int: String] = [:]
var rxIndex: Int?
let verbose = switch CommandLine.arguments.last {
case "-v": 1
case "-vv": 2
case "-vvv": 3
default: 0
}
func readInput() -> [Module] {
let broadcast = "broadcaster"
var modules = [String: (partial: Module, outputs: [String])]()
while let line = readLine() {
let words = line.split { !$0.isLetter }
let name = String(words.first!)
let partial: Module? = switch line.first {
case "%": .flip("", [], 0)
case "&": .conjunction("", [], [], 0)
default: name == broadcast ? .broadcast("", []) : .other(name)
}
let outputs = Array(words.dropFirst(1).map { String($0) })
modules[name] = (partial!, outputs)
}
var uniqueNames = Set(modules.keys)
var inputs = [String: Set<String>]()
for (name, parsed) in modules {
for output in parsed.outputs {
uniqueNames.insert(output)
inputs[output, default: Set()].insert(name)
}
}
// Ensure broadcast is at index 0
uniqueNames.remove(broadcast)
let keys = [broadcast] + (Array(uniqueNames).sorted())
var result = [Module]()
for name in keys {
let parsed = modules[name]
let js = parsed?.outputs.map { keys.firstIndex(of: $0)! }
switch parsed?.partial {
case .broadcast:
result.append(.broadcast(name, js!))
case .other:
result.append(.other(name))
case nil:
result.append(.other(name))
case .flip:
result.append(.flip(name, js!, 0))
case .conjunction:
var state = UInt64.max
let ins = inputs[name]!
var ik = [Int]()
for input in ins {
let k = keys.firstIndex(of: input)!
ik.append(k)
state ^= (1 << k)
}
result.append(.conjunction(name, ik, js!, state))
}
modulesIndexToName[result.count - 1] = name
if name == "rx" {
rxIndex = result.count - 1
}
}
return result
}
struct Pulse {
let value: Bool
let from: Int
let to: Int
}
extension Pulse: CustomStringConvertible {
var description: String {
let f = from == -1 ? "button" : modulesIndexToName[from]!
let t = modulesIndexToName[to]!
let v = value ? "high" : "low"
return "\(f) -\(v)-> \(t)"
}
}
func propogate(pulse: Pulse, module: Module) -> ([Pulse], Module)? {
func emit(_ value: Bool, _ outputs: [Int]) -> [Pulse] {
outputs.map { Pulse(value: value, from: pulse.to, to: $0 ) }
}
func toggle(_ s: UInt8) -> UInt8 {
s == 0 ? 1 : 0
}
switch module {
case .other: return nil
case .broadcast(_, let outputs): return (emit(pulse.value, outputs), module)
case .flip(let name, let outputs, var state):
if pulse.value { return nil }
else {
state = toggle(state)
return (emit(state == 1, outputs), .flip(name, outputs, state))
}
case .conjunction(let name, let ik, let outputs, var state):
if pulse.value {
state |= (1 << pulse.from)
} else {
state &= ~(1 << pulse.from)
}
let value = state != .max
return (emit(value, outputs), .conjunction(name, ik, outputs, state))
}
}
func simulate(modules: inout [Module]) -> (Int, Int) {
let buttonPress = Pulse(value: false, from: -1, to: 0)
showPreamble(modules: modules)
var (ct, cf) = (0, 0)
func count(_ pulse: Pulse) {
if (verbose > 2) {
print(pulse)
}
if pulse.value { ct += 1 }
else { cf += 1 }
}
var n = 0
var rxn: Int? = rxIndex == nil ? 0 : nil
while n < 1000 || rxn == nil {
n += 1
show(modules: modules)
var pending = [buttonPress]
var pi = 0
while pi < pending.count {
let pulse = pending[pi]
count(pulse)
pi += 1
if (pulse.to == rxIndex && !pulse.value) {
rxn = n
}
let module = modules[pulse.to]
if let (pulses, newModule) = propogate(pulse: pulse, module: module) {
modules[pulse.to] = newModule
pending.append(contentsOf: pulses)
}
}
}
if verbose > 1 {
print("counts", ct, cf)
}
return (ct * cf, rxn ?? 0)
}
func showPreamble(modules: [Module]) {
func padn(_ s: String, n: Int) -> String {
String((s + "---------------------").prefix(n))
}
if verbose == 1 {
var names = [String]()
for m in modules {
switch m {
case .flip(let name, _, _):
names.append(padn(name, n: 2))
case .conjunction(let name, let ik, _, _):
names.append(padn(name, n: max(ik.count + 1, 2)))
default: continue
}
}
print(names.joined(separator: ""))
}
}
func show(modules: [Module]) {
if verbose > 1 {
print(modules.map({ $0.description }).joined(separator: " · "))
} else if verbose > 0 {
print(modules.compactMap({ $0.stateString }).joined(separator: " "))
}
}
var modules = readInput()
let p1 = simulate(modules: &modules)
show(modules: modules)
print(p1)