view 2017/day13.d @ 15:817954f71d53

day 13: cache a calculation for speed
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Thu, 14 Dec 2017 10:36:38 -0500
parents 56b75b62d591
children
line wrap: on
line source

import std.stdio;
import std.algorithm: filter, map, sum;
import std.string: split;
import std.conv: to;
import std.array: array;

auto getHits(T)(T firewall, int init = 0) {
  return firewall.filter!(xy => (init + xy[0]) % xy[2] == 0);
}

auto computeSeverity(T)(T firewall) {
  return firewall.getHits.map!(xy => xy[0]*xy[1]).sum;
}

auto findPassing(T)(T firewall) {
  auto init = 0;
  while(! firewall.getHits(init).empty) {
    init++;
  }
  return init;
}

void main(string[] args) {
  auto firewall = File(args[1]).byLineCopy.map!(
    function(string x){
      auto v = x.split(": ").map!(to!int);
      return v.array ~ (2*v[1] - 2);
    }
  ).array;
  writeln(firewall.computeSeverity);
  writeln(firewall.findPassing);
}