r/adventofcode • • Dec 03 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 3 Solutions -πŸŽ„-

--- Day 3: Spiral Memory ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

21 Upvotes

297 comments sorted by

View all comments

1

u/Scroph Dec 04 '17

D solution, first part only. I hope no one will read this :

import std.stdio;
import std.math;
import std.typecons;
import std.string;
import std.conv;

alias Vec2D = Tuple!(int, int);
enum Direction {up, down, left, right}
void main()
{
    foreach(line; stdin.byLine)
    {
        int n = line.strip.to!int;
        n.solve.writeln;
    }
}

int solve(int input)
{
    int square;
    Vec2D offset;
    input.closest_square(offset, square);
    int d = offset[0];
    auto direction = Direction.left;
    
    while(square != input)
    {
        final switch(direction) with(Direction)
        {
            case left:	offset[0]--; break;
            case right:	offset[0]++; break;
            case up:	offset[1]--; break;
            case down:	offset[1]++; break;
        }

        if(offset == tuple(-d, d))
            direction = Direction.up;
        else if(offset == tuple(d, -d))
            direction = Direction.down;
        else if(offset == tuple(-d, -d))
            direction = Direction.right;

        square--;
    }

    return offset[0].abs + offset[1].abs;
}

void closest_square(int input, out Vec2D offset, out int square)
{
    int i, j;
    for(i = 1; i * i < input; i += 2)
        j++;
    
    offset[0] = j;
    offset[1] = j;
    square = i ^^ 2;
}

unittest
{
    int n = 39;
    int square;
    Vec2D offset;
    n.closest_square(offset, square);
    assert(square == 49);
    assert(offset == tuple(3, 3));
}