comparison 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
comparison
equal deleted inserted replaced
2:4620ff0a058c 3:b5533de6ff5b
1 import std.stdio;
2 import std.math: realabs=abs;
3 import std.complex;
4 import std.conv: to;
5
6 auto generateSpiral(numType)(numType x) {
7 auto z = Complex!numType(0);
8 auto i = Complex!numType(0, 1);
9 auto direction = Complex!numType(1);
10 numType stepsTillTurn = 1, stepsTaken = 0;
11 bool maxedOnce = false;
12
13 auto result = [z];
14
15 for(numType steps = 1; steps < x; steps++) {
16 z += direction;
17 stepsTaken++;
18 result ~= z;
19 if(stepsTaken == stepsTillTurn) {
20 // Time to turn
21 direction *= i;
22 stepsTaken = 0;
23 if(maxedOnce) {
24 stepsTillTurn++;
25 maxedOnce = false;
26 }
27 else {
28 maxedOnce = true;
29 }
30 }
31 }
32 return result;
33 }
34
35 auto tallySpiral(numType)(Complex!numType[] spiral) {
36 auto tally = [numType(1)];
37
38 for(auto i = 1; i < spiral.length; i++) {
39 numType sum = 0;
40 auto z = spiral[i];
41 for(auto j = 0; j < i; j++) {
42 auto w = spiral[j];
43 if(abs(w - z) < 2) {
44 sum += tally[j];
45 }
46 }
47 tally ~= sum;
48 }
49
50 return tally;
51 }
52
53 void main(string[] args){
54 auto target = to!double(args[1]);
55 auto spiral = generateSpiral(target);
56 auto end = spiral[$-1];
57 writeln(realabs(end.re) + realabs(end.im));
58 auto tally = tallySpiral(spiral);
59 writeln(tally);
60 }