r/adventofcode • • Dec 11 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 11 Solutions -๐ŸŽ„-

--- Day 11: Hex Ed ---


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!

20 Upvotes

253 comments sorted by

View all comments

2

u/TominatorBE Dec 11 '17

PHP

Instead of 3D grids (which I thought about but it's too early in the morning to properly imagine them), I used a 2D grid where there are 'half' steps... So 'n' goes + 2, while 'ne' and 'nw' go + 1.

Part 1:

function run_the_code($input) {
	$moves = explode(',', $input);

	$x = 0;
	$y = 0;

	foreach ($moves as $move) {
		switch ($move) {
			case 'n':
				$y += 2;
				break;
			case 'ne':
				$y += 1;
				$x++;
				break;
			case 'nw':
				$y += 1;
				$x--;
				break;
			case 's':
				$y -= 2;
				break;
			case 'se':
				$y -= 1;
				$x++;
				break;
			case 'sw':
				$y -= 1;
				$x--;
				break;
		}
	}

	return (abs($x) + abs($y)) / 2;
}

Part 2:

function run_the_code($input) {
	$moves = explode(',', $input);

	$x = 0;
	$y = 0;

	$furthest = 0;

	foreach ($moves as $move) {
		switch ($move) {
			case 'n':
				$y += 2;
				break;
			case 'ne':
				$y += 1;
				$x++;
				break;
			case 'nw':
				$y += 1;
				$x--;
				break;
			case 's':
				$y -= 2;
				break;
			case 'se':
				$y -= 1;
				$x++;
				break;
			case 'sw':
				$y -= 1;
				$x--;
				break;
		}

		$furthest = max($furthest, (abs($x) + abs($y)) / 2);
	}

	return $furthest;
}

1

u/kratskij Dec 11 '17

I did the exact same thing (except using 1 and 0.5 instead of 2 and 1), also in PHP. I discovered later that this is incorrect, though. Try using "ne,se,ne,se,ne,se" as input. Should be 6. Will be 3. I guess we were both lucky with our inputs :D

1

u/TominatorBE Dec 11 '17

lol I guess we were :D

1

u/sushiguru Dec 21 '17

Similar approach, but using an array of vectors:

function part_1($input){
$vectors = array(
    'n'=>['x'=>0,'y'=>2],
    'ne'=>['x'=>1,'y'=>1],
    'se'=>['x'=>1,'y'=>-1],
    's'=>['x'=>0,'y'=>-2],
    'sw'=>['x'=>-1,'y'=>-1],
    'nw'=>['x'=>-1,'y'=>1]
    );
$steps = explode(',',$input);
$x = 0;
$y = 0;

foreach($steps as $step){
    
    $x += $vectors[$step]['x'];
    $y += $vectors[$step]['y'];

}

$result = (abs($x)+abs($y))/2;
return $result;
}

1

u/TominatorBE Dec 21 '17

Keep in mind that my code is wrong in the general case, as explained in other threads :( But your code is also easily adaptable to work correctly, by using a 'z' index as well.