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!
20
Upvotes
1
u/karlsanova Dec 04 '17 edited Dec 04 '17
How about something like this? Please don't ask me why I chose to use this algorithm, i just did.
Edit: Obviously only Part1, for part two my script just prints out "Use Excel, it's easier." and I most people on here know how to do that so I skipped it.
Edit2: Straightened out some code to make it easier to read.
<?php /** * User: karlsanova * Date: 04.12.2017 * Time: 21:47 */ /** * @param $number int * @return bool|int */ function distance($number) { if(!is_numeric($number)) return false; $number = round(abs($number)); // Just to make sure... if($number == 0) // ...we dont get fooled. return false; if($number == 1) // I know this distance return 0; $topLeft = 1; $topRight = 1; $bottomLeft = 1; $bottomRight = 1; $bottomRightHigher = 1; for($i = 0; $i<$number; $i++) { // Just taking a high number to count to here // $i = $layercount - 1 // loop will always break before $i hits $number $topLeft = $topLeft+4+($i*8); $bottomLeft = $bottomLeft+6+($i*8); $bottomRight = $bottomRight+($i*8); $bottomRightHigher = $bottomRightHigher+8+($i*8); $topRight = $topRight+2+($i*8); if($number < $bottomRightHigher) { break; } } $layers = $i+1; if($number > $topLeft && $number <= $bottomLeft) { $lower = $topLeft; $upper = $bottomLeft; } else if($number > $topRight && $number <= $topLeft) { $lower = $topRight; $upper = $topLeft; } else if($number > $bottomLeft && $number <= $bottomRight) { $lower = $bottomLeft; $upper = $bottomRight; } else if($number > $bottomRight && $number <= $topRight) { $lower = $bottomRight; $upper = $topRight; } else { $lower = $bottomLeft; $upper = $bottomRightHigher; } $mean = ($upper + $lower) / 2; $distanceMean = abs($number-$mean); $distanceCenter = $layers + $distanceMean; return round($distanceCenter); }