Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio;
- import std.regex;
- import std.string;
- import std.conv;
- class RegisterMachine {
- uint[1024] registers;
- void input(uint[] data) {
- this.registers[1..data.length+1] = data;
- return;
- }
- void run(uint[][] program) {
- uint step = 1;
- while (true) {
- if (step == 0) {
- break;
- }
- switch (program[step][1]) {
- case 1:
- ++this.registers[program[step][0]];
- step = program[step][2];
- break;
- case 0:
- if (this.registers[program[step][0]] == 0) {
- step = program[step][3];
- }
- else {
- --this.registers[program[step][0]];
- step = program[step][2];
- }
- break;
- default:
- break;
- }
- }
- writeln(this.registers[0..16]);
- return;
- }
- }
- uint[][] parseProgram(string file) {
- auto f = File(file);
- auto r = regex(r"[+\-\w]+");
- uint[][] program = [[0]];
- foreach (line; f.byLine()) {
- auto commentLoc = line.indexOf("#");
- if (commentLoc == -1) {
- commentLoc = line.length;
- }
- uint[] instruction;
- foreach (symbol; matchAll(line[0..commentLoc], r)) {
- switch (symbol[0]) {
- case "+":
- instruction ~= 1;
- break;
- case "-":
- instruction ~= 0;
- break;
- default:
- instruction ~= to!uint(symbol[0]);
- break;
- }
- }
- program ~= instruction;
- }
- return program;
- }
- void main(string[] args) {
- auto rm = new RegisterMachine();
- rm.input([9999, 9999]);
- rm.run(parseProgram(args[1]));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement