view 2017/day11/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.array: array;
import std.math: abs;
import std.string: chomp, split;
import std.algorithm: max, map, cumulativeFold, maxElement;
import std.stdio;

immutable int[2][string] directions;

pure static this(){
  directions = [
    "ne": [1,1],
    "n": [0,1],
    "nw": [-1,0],
    "sw": [-1,-1],
    "s": [0,-1],
    "se": [1,0],
  ];
}

auto hexNorm(int x, int y) {
  if (x*y < 0) {
    return abs(x) + abs(y);
  }
  return max(abs(x), abs(y));
}

void main(string[] args) {
  auto norms =
    File(args[1]).readln.chomp.split(",").map!(x => directions[x])
    .cumulativeFold!((a, b) => [a[0] + b[0], a[1] + b[1]])([0, 0])
    .map!(xy => hexNorm(xy[0], xy[1]))
    .array;
  writeln(norms[$-1]);
  writeln(norms.maxElement);
}