view 2017/day08/app.d @ 35:1d99d733cf13 default tip @

day08: replace static foreach with workaround
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Tue, 16 Jan 2018 11:28:55 -0500
parents bc652fa0a645
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;
bool function(int,int)[string] comparisons;

auto getComparisons(Args...)() {
  foreach(cmp; Args) {
    comparisons[cmp] = mixin("function(int a, int b) => a "~cmp~" b");
  }
  return comparisons;
}

shared static this() {
  comparisons = getComparisons!("<", ">", "==", "<=", ">=", "!=");
}

void evalInstruction(string line) {
  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);
}