Mercurial > hg > aoc
changeset 2:4620ff0a058c
day 3
author | Jordi Gutiérrez Hermoso <jordigh@octave.org> |
---|---|
date | Thu, 07 Dec 2017 11:44:51 -0500 |
parents | 772b9f146b20 |
children | b5533de6ff5b |
files | 2017/03/app.d |
diffstat | 1 files changed, 60 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
new file mode 100644 --- /dev/null +++ b/2017/03/app.d @@ -0,0 +1,60 @@ +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); +}