-
Notifications
You must be signed in to change notification settings - Fork 0
/
Intcode.cs
386 lines (352 loc) · 10.9 KB
/
Intcode.cs
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Threading.Tasks;
class Intcode : IIntcode {
enum State {
Ready, //Program is created, has never been run
Paused, //Program has been run, but has been paused and is ready to run some more
Waiting, //Program is waiting for additional input
Finished //Program has finished execution
}
enum ParameterMode {
Position,
Immediate,
Relative
}
readonly Memory memory;
State state = State.Ready;
bool isWaitedOn = false;
int i = 0; //Memory pointer
int relativeBase = 0;
public IIntcode Input { get; set; }
public IIntcode Output { get; set; }
public Queue<BigInteger> InQueue { get; set; }
public Queue<BigInteger> OutQueue { get; set; }
readonly bool blocking;
public void SetInput(IIntcode input) {
Input = input;
input.Output = this;
InQueue = input.OutQueue;
}
public void SetInput(Queue<BigInteger> inQueue) {
if (!(Input is null)) {
Input.Output = null;
Input = null;
}
InQueue = inQueue;
}
public void SetOutput(IIntcode output) {
Output = output;
output.Input = this;
OutQueue = output.InQueue;
}
public void SetOutput(Queue<BigInteger> outQueue) {
if (!(Output is null)) {
Output.Input = null;
Output = null;
}
OutQueue = outQueue;
}
public Intcode(string fileName, bool blocking = true) : this(Array.ConvertAll(File.ReadAllText(fileName).Split(','), BigInteger.Parse), blocking) { }
public Intcode(BigInteger[] memory, bool blocking = true) : this(new Memory(memory), blocking) { }
public Intcode(Memory memory, bool blocking = true) {
this.memory = memory;
this.blocking = blocking;
}
//Duplicate doesn't keep IO references, it only copies the queues, if present
public Intcode Duplicate() {
if (state != State.Ready) {
throw new InvalidOperationException("Can't duplicate an already started program.");
}
Intcode duplicate = new Intcode(memory.Clone(), blocking);
if (!(InQueue is null)) {
duplicate.InQueue = new Queue<BigInteger>(InQueue);
}
if (!(OutQueue is null)) {
duplicate.OutQueue = new Queue<BigInteger>(OutQueue);
}
return duplicate;
}
public void Continue() {
if (state == State.Ready || state == State.Paused) {
Run();
}
}
public int Run() {
//Check state before running
switch (state) {
case State.Finished:
throw new InvalidOperationException("Attempted to Run a Finished program.");
case State.Waiting:
throw new InvalidOperationException("Attempted to Run a program Waiting for input. This is invalid and might cause infinite recursion.");
}
while (true) {
int op = (int)(memory[i] % 100);
ParameterMode mode1 = (ParameterMode)(int)(memory[i] % 1000 / 100);
ParameterMode mode2 = (ParameterMode)(int)(memory[i] % 10000 / 1000);
ParameterMode mode3 = (ParameterMode)(int)(memory[i++] % 100000 / 10000); //Increment on last one
switch (op) {
//Addition
case 1:
BigInteger sum = NextParameter(mode1) + NextParameter(mode2);
memory[NextPosition(mode3)] = sum;
break;
//Multiplication
case 2:
BigInteger product = NextParameter(mode1) * NextParameter(mode2);
memory[NextPosition(mode3)] = product;
break;
//Input
case 3:
if (!blocking) {
if (InQueue != null && InQueue.Count > 0) {
memory[NextPosition(mode1)] = InQueue.Dequeue();
} else {
memory[NextPosition(mode1)] = -1;
}
break;
}
if (InQueue is null) { //No queue, got to ask from user
Console.WriteLine("Input integer:");
memory[NextPosition(mode1)] = int.Parse(Console.ReadLine());
} else { //Have queue, try to take from that
if (InQueue.Count == 0) { //Queue is empty
if (Input is null) { //And nothing to give me more input - must crash
throw new IOException("Input queue empty - stuck waiting for input.");
} else { //Have backing input program, ask from that
state = State.Waiting;
Input.RequestInput();
memory[NextPosition(mode1)] = InQueue.Dequeue();
}
} else { //Queue isn't empty, take from it and move on
memory[NextPosition(mode1)] = InQueue.Dequeue();
}
}
break;
//Output
case 4:
if (OutQueue is null) { //No queue, printing to console
Console.WriteLine(NextParameter(mode1));
} else { //Have queue, add to that
OutQueue.Enqueue(NextParameter(mode1));
if (isWaitedOn) { //Return control to calling method if waited on
isWaitedOn = false;
state = State.Paused;
return 1;
}
}
break;
//Jump if non-zero
case 5:
if (NextParameter(mode1) != 0) {
i = (int)NextParameter(mode2);
} else {
i++;
}
break;
//Jump if zero
case 6:
if (NextParameter(mode1) == 0) {
i = (int)NextParameter(mode2);
} else {
i++;
}
break;
//Less than
case 7:
BigInteger b = NextParameter(mode1) < NextParameter(mode2) ? 1 : 0;
memory[NextPosition(mode3)] = b;
break;
//Equality
case 8:
b = NextParameter(mode1) == NextParameter(mode2) ? 1 : 0;
memory[NextPosition(mode3)] = b;
break;
case 9:
relativeBase += (int)NextParameter(mode1);
break;
//Halt
case 99:
state = State.Finished;
Output?.Continue();
return 0;
}
}
}
public async Task<int> RunAsync() {
//Check state before running
switch (state) {
case State.Finished:
throw new InvalidOperationException("Attempted to Run a Finished program.");
case State.Waiting:
throw new InvalidOperationException("Attempted to Run a program Waiting for input. This is invalid and might cause infinite recursion.");
}
while (true) {
int op = (int)(memory[i] % 100);
ParameterMode mode1 = (ParameterMode)(int)(memory[i] % 1000 / 100);
ParameterMode mode2 = (ParameterMode)(int)(memory[i] % 10000 / 1000);
ParameterMode mode3 = (ParameterMode)(int)(memory[i++] % 100000 / 10000); //Increment on last one
switch (op) {
//Addition
case 1:
BigInteger sum = NextParameter(mode1) + NextParameter(mode2);
memory[NextPosition(mode3)] = sum;
break;
//Multiplication
case 2:
BigInteger product = NextParameter(mode1) * NextParameter(mode2);
memory[NextPosition(mode3)] = product;
break;
//Input
case 3:
if (!blocking) {
await Task.Delay(1);
if (InQueue != null && InQueue.Count > 0) {
lock (InQueue) {
memory[NextPosition(mode1)] = InQueue.Dequeue();
}
} else {
memory[NextPosition(mode1)] = -1;
}
break;
}
if (InQueue is null) { //No queue, got to ask from user
Console.WriteLine("Input integer:");
memory[NextPosition(mode1)] = int.Parse(Console.ReadLine());
} else { //Have queue, try to take from that
if (InQueue.Count == 0) { //Queue is empty
if (Input is null) { //And nothing to give me more input - must crash
throw new IOException("Input queue empty - stuck waiting for input.");
} else { //Have backing input program, ask from that
for (int delay = 1; InQueue.Count == 0; delay++) {
await Task.Delay(delay); //increasing delay, waiting for input
}
lock (InQueue) {
memory[NextPosition(mode1)] = InQueue.Dequeue();
}
}
} else { //Queue isn't empty, take from it and move on
lock (InQueue) {
memory[NextPosition(mode1)] = InQueue.Dequeue();
}
}
}
break;
//Output
case 4:
if (OutQueue is null) { //No queue, printing to console
Console.WriteLine(NextParameter(mode1));
} else { //Have queue, add to that
lock (OutQueue) {
OutQueue.Enqueue(NextParameter(mode1));
}
}
break;
//Jump if non-zero
case 5:
if (NextParameter(mode1) != 0) {
i = (int)NextParameter(mode2);
} else {
i++;
}
break;
//Jump if zero
case 6:
if (NextParameter(mode1) == 0) {
i = (int)NextParameter(mode2);
} else {
i++;
}
break;
//Less than
case 7:
BigInteger b = NextParameter(mode1) < NextParameter(mode2) ? 1 : 0;
memory[NextPosition(mode3)] = b;
break;
//Equality
case 8:
b = NextParameter(mode1) == NextParameter(mode2) ? 1 : 0;
memory[NextPosition(mode3)] = b;
break;
case 9:
relativeBase += (int)NextParameter(mode1);
break;
//Halt
case 99:
state = State.Finished;
Output?.Continue();
return 0;
}
}
}
public void RequestInput() {
switch (state) {
case State.Waiting:
throw new IOException("Circular input waiting loop encountered - deadlocked.");
case State.Finished:
throw new IOException("Input suppling program has finished execution - stuck waiting for input.");
default:
isWaitedOn = true;
if (Run() == 0) { //Input finished execution without returning input
throw new IOException("Input suppling program has finished execution - stuck waiting for input.");
}
return; //Successfully got input
}
}
public int RunDuplicate() => Duplicate().Run();
BigInteger NextParameter(ParameterMode mode) {
switch (mode) {
case ParameterMode.Position:
return memory[(int)memory[i++]];
case ParameterMode.Immediate:
return memory[i++];
case ParameterMode.Relative:
return memory[(int)memory[i++] + relativeBase];
default:
throw new ArgumentException($"Unknown parameter mode {mode} near memory address {i}");
}
}
int NextPosition(ParameterMode mode) {
switch (mode) {
case ParameterMode.Position:
return (int)memory[i++];
case ParameterMode.Relative:
return (int)memory[i++] + relativeBase;
default:
throw new ArgumentException($"Unknown or invalid position mode {mode} near memory address {i}");
}
}
public static int RunFromFile(string fileName) => new Intcode(fileName).Run();
}
class Memory {
BigInteger[] memory;
public BigInteger this[int i] {
get => i >= memory.Length ? 0 : memory[i];
set {
if (i >= memory.Length) {
Array.Resize(ref memory, i + 1);
}
memory[i] = value;
}
}
public Memory(BigInteger[] memory) {
this.memory = memory;
}
public Memory Clone() => new Memory((BigInteger[])memory.Clone());
}
interface IIntcode {
IIntcode Input { get; set; }
IIntcode Output { get; set; }
Queue<BigInteger> InQueue { get; set; }
Queue<BigInteger> OutQueue { get; set; }
/// <summary>
/// Input MUST populate the shared OutQueue before returning.
/// </summary>
void RequestInput();
/// <summary>
/// Output MAY continue execution as if started normally.
/// </summary>
void Continue();
}