view 2017/day22/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.stdio;
import std.complex;
import std.array: array;

// Clean represented by absence
enum state {weak, infect, flag};

auto parseGrid(string[] lines) {
  long mid = lines.length/2;
  state[Complex!double] grid;
  foreach(int j, line; lines) {
    foreach(int i, c; line) {
      if(c == '#') {
        grid[Complex!double(i-mid, mid-j)] = state.infect;
      }
    }
  }
  return grid;
}

auto walkGrid(state[Complex!double] grid, size_t maxiter) {
  auto
    pos = Complex!double(0, 0),
    facing = Complex!double(0, 1),
    left = Complex!double(0, 1),
    right = Complex!double(0, -1),
    back = Complex!double(-1, 0);
  size_t infected = 0;
  foreach(_; 0..maxiter) {
    if(pos in grid) {
      final switch(grid[pos]) {
      case state.weak:
        grid[pos] = state.infect;
        infected++;
        break;
      case state.infect:
        grid[pos] = state.flag;
        facing *= right;
        break;
      case state.flag:
        grid.remove(pos);
        facing *= back;
        break;
      }
    }
    else {
      grid[pos] = state.weak;
      facing *= left;
    }
    pos += facing;
  }
  return infected;
}

void main(string[] args) {
  auto grid = File(args[1]).byLineCopy.array.parseGrid;
  writeln(grid.walkGrid(10000000));
}