Switch to using OS pipes

This commit is contained in:
2019-12-07 21:26:59 +00:00
parent 325ec9d591
commit ea094368e7
3 changed files with 73 additions and 48 deletions

View File

@@ -136,42 +136,74 @@ pub fn main() anyerror!void {
// 5 intcode computers act as the amps
var machines: [5]intcode.Machine = undefined;
// Allocate memory once only.
for (machines) |*machine| {
machine.alloc = alloc;
machine.memory = try alloc.alloc(i32, program.len);
}
// Now wire up the machines correctly. The output of each machine should be
// the input to the next.
const pipes: [6]intcode.CharDev = .{
try std.os.pipe(),
try std.os.pipe(),
try std.os.pipe(),
try std.os.pipe(),
try std.os.pipe(),
try std.os.pipe(),
};
machines[0].input = pipes[0];
machines[0].output = pipes[1];
machines[1].input = machines[0].output;
machines[1].output = pipes[2];
machines[2].input = machines[1].output;
machines[2].output = pipes[3];
machines[3].input = machines[2].output;
machines[3].output = pipes[4];
machines[4].input = machines[3].output;
machines[4].output = pipes[5];
// 120 phase permutations. Find the highest.
var max: i32 = 0;
for (perm1) |inputs| {
for (machines) |*machine| {
var copy = try alloc.alloc(i32, program.len);
std.mem.copy(i32, copy, program);
machine.* = try intcode.Machine.init(alloc, copy);
std.mem.copy(i32, machine.memory, program);
machine.ip = 0;
}
// Phase input
// Phase inputs
for (inputs) |input, i| {
try machines[i].writeToInput(input);
}
// amplifier input
for (machines) |*machine, i| {
var ampInput: i32 = 0;
if (i > 0) ampInput = try machines[i - 1].readFromOutput(false);
// Provide starting value of 0
try machines[0].writeToInput(0);
try machine.writeToInput(ampInput);
// run the program
for (machines) |*machine, i| {
try machine.run();
}
const final = try machines[4].readFromOutput(false);
const final = try machines[4].readFromOutput();
if (final > max)
max = final;
// Don't forget to free everything!
for (machines) |*machine, i| {
alloc.free(machine.memory);
machine.deinit();
}
}
std.debug.warn("Day 7, Part 1: {}\n", max);
// In part 2, the machines need to be wired into a feedback loop
// In part 2, the machines need to be wired into a feedback loop.
// To do this, drop pipe 6 and replace it with pipe 0
std.os.close(pipes[5][0]);
std.os.close(pipes[5][1]);
machines[4].output = machines[0].input;
}