view 2017/day03.d @ 3:b5533de6ff5b

move all app.d's to top level
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Thu, 07 Dec 2017 11:44:52 -0500
parents 2017/03/app.d@4620ff0a058c
children
line wrap: on
line source

import std.stdio;
import std.math: realabs=abs;
import std.complex;
import std.conv: to;

auto generateSpiral(numType)(numType x) {
  auto z = Complex!numType(0);
  auto i = Complex!numType(0, 1);
  auto direction = Complex!numType(1);
  numType stepsTillTurn = 1, stepsTaken = 0;
  bool maxedOnce = false;

  auto result = [z];

  for(numType steps = 1; steps < x; steps++) {
    z += direction;
    stepsTaken++;
    result ~= z;
    if(stepsTaken == stepsTillTurn) {
      // Time to turn
      direction *= i;
      stepsTaken = 0;
      if(maxedOnce) {
        stepsTillTurn++;
        maxedOnce = false;
      }
      else {
        maxedOnce = true;
      }
    }
  }
  return result;
}

auto tallySpiral(numType)(Complex!numType[] spiral) {
  auto tally = [numType(1)];

  for(auto i = 1; i < spiral.length; i++) {
    numType sum = 0;
    auto z = spiral[i];
    for(auto j = 0; j < i; j++) {
      auto w = spiral[j];
      if(abs(w - z) < 2) {
        sum += tally[j];
      }
    }
    tally ~= sum;
  }

  return tally;
}

void main(string[] args){
  auto target = to!double(args[1]);
  auto spiral = generateSpiral(target);
  auto end = spiral[$-1];
  writeln(realabs(end.re) + realabs(end.im));
  auto tally = tallySpiral(spiral);
  writeln(tally);
}