view 2017/day09/app.d @ 33:bc652fa0a645

Move all solutions to per-day subdirs
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Tue, 09 Jan 2018 21:50:37 -0500
parents 2017/day09.d@18e7ffa83a14
children
line wrap: on
line source

import std.stdio;
import std.range;

auto parseStream(string stream) {
  bool quoted = false;
  bool escape = false;
  int sum = 0;
  int garbage = 0;
  int depth = 0;
  foreach(c; stream) {
    if(escape) {
      escape = false;
      continue;
    }
    else if(quoted) {
      switch(c) {
      case '>':
        quoted = false;
        break;
      case '!':
        escape = true;
        break;
      default:
        garbage++;
      }
    }
    else {
      switch(c) {
      case '{':
        depth++;
        break;
      case '}':
        sum += depth;
        depth--;
        break;
      case '<':
        quoted = true;
        break;
      default:
      }
    }
  }

  return [sum, garbage];
}

void main(string[] args){
  writeln(File(args[1]).readln.parseStream);
}