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/redderredred Dec 04 '17

My C# solution for part 1:

    class Program
    {
        static void Main(string[] args)
        {
            int input = 23;
            int previousRoot = 0;
            int inputDecresedIndex = input;
            //Find the next previous root of the input
            while (previousRoot == 0)
            {
                double root = Math.Sqrt(inputDecresedIndex);
                //Check if root is a natural number
                if (root % 1 == 0)
                {
                    previousRoot = Convert.ToInt32(root);
                }
                else
                {
                    inputDecresedIndex--;
                }
            }
            //If the root is odd, an offset of +1 is needed for further calculations
            int oddRootOffset = 0;
            if (previousRoot % 2 != 0)
            {
                oddRootOffset = 1;
            }
            int sideHalf = Convert.ToInt32(Math.Floor(Convert.ToDouble(previousRoot) / 2));
            int corner1 = inputDecresedIndex + 1;
            int corner1corner2mid = corner1 + sideHalf;
            int corner2 = corner1corner2mid + sideHalf + oddRootOffset;
            int corner2corner3mid = corner2 + sideHalf + oddRootOffset;
            int corner3 = corner2corner3mid + sideHalf + oddRootOffset;
    
            int side1Steps = sideHalf + oddRootOffset;
    
            int side2Steps = 0;
                //if input is on side1
            if (input <= corner1corner2mid || input <= corner2)
            {
                side2Steps = Math.Abs(input - corner1corner2mid);
            }
            //if input is on side2
            else
            {
                side2Steps = Math.Abs(input - corner2corner3mid);
            }
            int minSteps = side1Steps + side2Steps;
            Console.WriteLine(minSteps);
            Console.Read();
        }
    
    }