view 2017/day19.d @ 25:836d284fff87

day 19
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Tue, 19 Dec 2017 11:17:40 -0500
parents
children
line wrap: on
line source

import std.stdio;
import std.array: array;
import std.algorithm: map;
import std.string: indexOf;
import std.typecons: tuple;

auto walkPath(T)(T grid) {
  char[] path;
  long i = grid[0].indexOf("|"), j = 1;
  int steps = 1;
  enum DIR {u, d, l, r};
  DIR dir = DIR.d;
  while(i > 0) {
    steps++;
    auto next = grid[j][i];

    switch(next) {
    case 'A': .. case 'Z':
      path ~= next;
      break;
    case '+':
      if(dir == DIR.u || dir == DIR.d) {
        if(grid[j][i-1] == '-') {
          dir = DIR.l;
        }
        else {
          dir = DIR.r;
        }
      }
      else {
        if(grid[j-1][i] == '|') {
          dir = DIR.u;
        }
        else {
          dir = DIR.d;
        }
      }
      break;
    default:
    }

    final switch(dir){
    case DIR.d:
      j++;
      break;
    case DIR.u:
      j--;
      break;
    case DIR.l:
      i--;
      break;
    case DIR.r:
      i++;
      break;
    }

  }
  return tuple(path, steps);
}

void main(string[] args) {
  auto grid = File(args[1]).byLineCopy.array.dup;
  auto ret = grid.walkPath;
  writeln(ret[0]);
  writeln(ret[1]);
}