view 2017/day16.d @ 21:f1f0220b5f7c

day 16: simply loop
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Sat, 16 Dec 2017 23:47:26 -0500
parents 8d1edc9efcb4
children
line wrap: on
line source

import std.stdio;
import std.algorithm: swap, bringToFront, map, find, canFind;
import std.string: split, indexOf;
import std.conv: to;
import std.range: iota, join, zip;
import std.array: array;

auto parseOps(string[] ops, string progsin) {
  // ubyte[] not char[] because https://issues.dlang.org/show_bug.cgi?id=16959
  auto progs = cast(ubyte[]) progsin.dup;
  foreach(op; ops) {
    switch(op[0]) {
    case 's':
      auto rot = to!int(op[1..$]);
      bringToFront(progs[rot..$], progs[0..rot]);
      break;
    case 'x':
      auto idx = op[1..$].split("/").map!(to!int);
      swap(progs[idx[0]], progs[idx[1]]);
      break;
    case 'p':
      auto AB = op[1..$].split("/");
      swap(find(progs, AB[0])[0], find(progs, AB[1])[0]);
      break;
    default:
    }
  }
  return cast(string) progs.idup;
}

auto iteratePerm(string[] ops, string progs) {
  string[] seenprogs;
  for(string result = progs;
      !seenprogs.canFind(result);
      result = ops.parseOps(result)) {
    seenprogs ~= result;
  }
  return seenprogs[1_000_000_000 % seenprogs.length];
}

void main(string[] args){
  auto ops = File(args[1]).byLineCopy.front.split(",");
  auto progs = "abcdefghijklmnop";
  writeln(ops.parseOps(progs));
  writeln(ops.iteratePerm(progs));
}