r/adventofcode • u/daggerdragon • 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^Β€?
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
View all comments
Show parent comment
1
u/tlareg Jan 04 '18
Yes, of course! :) I will try to explain my solution (sorry for my english).
My approach is very simple, I want to generate spiral of numbers step by step from 1 to 361527 (which is my input), all the time tracking number coordinates in cartesian grid. For number 1: x=0, y=0, for number 2: x=1, y=0 (I am moving right).
Function "move" is changing coordinates depending on my current direction (R - right, L - left, U - up, D - down).
If I get to the edge of spiral, I must change direction - "shouldChangeDir" function is determining that based on current cooridnates, current direction and current size of spiral. Next direction is always for Right - Up, for Up - Left, for Left - Down, for Down - Right (bacause it is how you can draw that spiral)
After number 2, I am changing direction to U - up. Now for number 3: x=1, y=-1. After changing direction 4 times, I must increase size of spiral edge (to know when I should change direction next time).
After finding coordinates (x,y) for my input number, I am computing manhattan distance between 1 and my input number, which is Math.abs(x) + Math.abs(y), and this is answer to first question.
To answer second question, I am generation very similar spiral of numbers, but this time I want compute sums of values in coordinates adjacent to my current coordinates. "computeSum" function is taking sums from adjacent coordinates and then I write this to "sums" map (because I must know what was previous sums to compute next sums in spiral).
When computed sum is finally larger than my puzzle input - this is second part answer.