Advertisement
Guest User

Untitled

a guest
Oct 11th, 2015
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.98 KB | None | 0 0
  1. import std.stdio;
  2. import std.regex;
  3. import std.string;
  4. import std.conv;
  5.  
  6. class RegisterMachine {
  7.     uint[1024] registers;
  8.  
  9.     void input(uint[] data) {
  10.         this.registers[1..data.length+1] = data;
  11.         return;
  12.     }
  13.  
  14.     void run(uint[][] program) {
  15.         uint step = 1;
  16.         while (true) {
  17.             if (step == 0) {
  18.                 break;
  19.             }
  20.             switch (program[step][1]) {
  21.                 case 1:
  22.                     ++this.registers[program[step][0]];
  23.                     step = program[step][2];
  24.                     break;
  25.                 case 0:
  26.                     if (this.registers[program[step][0]] == 0) {
  27.                         step = program[step][3];
  28.                     }
  29.                     else {
  30.                         --this.registers[program[step][0]];
  31.                         step = program[step][2];
  32.                     }
  33.                     break;
  34.                 default:
  35.                     break;
  36.             }
  37.         }
  38.         writeln(this.registers[0..16]);
  39.         return;
  40.     }
  41. }
  42.  
  43. uint[][] parseProgram(string file) {
  44.     auto f = File(file);
  45.     auto r = regex(r"[+\-\w]+");
  46.     uint[][] program = [[0]];
  47.     foreach (line; f.byLine()) {
  48.         auto commentLoc = line.indexOf("#");
  49.         if (commentLoc == -1) {
  50.             commentLoc = line.length;
  51.         }
  52.         uint[] instruction;
  53.         foreach (symbol; matchAll(line[0..commentLoc], r)) {
  54.             switch (symbol[0]) {
  55.                 case "+":
  56.                     instruction ~= 1;
  57.                     break;
  58.                 case "-":
  59.                     instruction ~= 0;
  60.                     break;
  61.                 default:
  62.                     instruction ~= to!uint(symbol[0]);
  63.                     break;
  64.             }
  65.         }
  66.         program ~= instruction;
  67.     }
  68.     return program;
  69. }
  70.  
  71.  
  72. void main(string[] args) {
  73.     auto rm = new RegisterMachine();
  74.     rm.input([9999, 9999]);
  75.     rm.run(parseProgram(args[1]));
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement