view 2017/day08.d @ 8:7d06d033b0ee

day 8
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Fri, 08 Dec 2017 17:21:23 -0500
parents
children
line wrap: on
line source

import std.algorithm: max, maxElement;
import std.regex;
import std.stdio;
import std.conv: to;

int[string] registers;
int maxSoFar = 0;

void evalInstruction(string line) {
  auto comparisons = [
    "<": function(int a, int b) => a < b,
    ">": function(int a, int b) => a > b,
    "==": function(int a, int b) => a == b,
    "<=": function(int a, int b) => a <= b,
    ">=": function(int a, int b) => a >= b,
    "!=": function(int a, int b) => a != b,
  ];
  static instructionRegex = regex(
    r"(?P<reg>\w+) (?P<op>inc|dec) (?P<amt>-?\d+) "
    ~ r"if (?P<condreg>\w+) (?P<comp>[=<>!]{1,2}) (?P<amtcond>-?\d+)"
  );
  auto row = matchFirst(line, instructionRegex);
  if(comparisons[row["comp"]](
       registers.get(row["condreg"], 0),
       to!int(row["amtcond"]))){
    if(row["op"] == "inc") {
      registers[row["reg"]] = registers.get(row["reg"], 0) + to!int(row["amt"]);
    }
    else if(row["op"] == "dec") {
      registers[row["reg"]] = registers.get(row["reg"], 0) - to!int(row["amt"]);
    }
  }
  maxSoFar = max(maxSoFar, registers.values.maxElement);
}

void main(string[] args) {
  foreach(line; File(args[1]).byLineCopy) {
    evalInstruction(line);
  }
  writeln(registers.values.maxElement);
  writeln(maxSoFar);
}