changeset 8:7d06d033b0ee

day 8
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Fri, 08 Dec 2017 17:21:23 -0500
parents 52fdca7ea9be
children 18e7ffa83a14
files 2017/day08.d
diffstat 1 files changed, 42 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/2017/day08.d
@@ -0,0 +1,42 @@
+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);
+}