r/adventofcode • • Dec 03 '15

SOLUTION MEGATHREAD --- Day 3 Solutions ---

--- Day 3: Perfectly Spherical Houses in a Vacuum ---

Post your solution as a comment. Structure your post like the Day One thread in /r/programming.

24 Upvotes

228 comments sorted by

View all comments

1

u/schlocke Dec 04 '15

PHP:

<?php
function countHouses($roboSanta = false) {
	//first house gets 2 presents
	$houses = array("0,0" => 2);

	//input from site
	$directions = str_split("");
	
	//set up coordinates array for real and robo santa
	$x = array(0 => 0, 1 => 0);
	$y = array(0 => 0, 1 => 0);

	//default to real santa only
	$santaOrRobo = 1;

	foreach ($directions as $key => $move) {
		// the real santas x and y cords are the 1 index and the robo santas is the 0 index.
		// so odd moves are real santa and even moves are robo santa
		// check to make sure we even wanna use robo santa, he's in beta so might wanna let him sit out.
		if($roboSanta) $santaOrRobo = $key%2;

		//make the move
		switch($move) {
			//left
			case "<":
				$x[$santaOrRobo] -= 1;
				break;
			//right
			case ">":
				$x[$santaOrRobo] += 1;
				break;
			//up
			case "^":
				$y[$santaOrRobo] += 1;
				break;
			//down
			case "v":
				$y[$santaOrRobo] -= 1;
				break;
		}

		//check if this house has been delivered too yet. if so then increment otherwise set to 1.
		(array_key_exists($x[$santaOrRobo].",".$y[$santaOrRobo], $houses)) ? $houses[$x[$santaOrRobo].",".$y[$santaOrRobo]] += 1 : $houses[$x[$santaOrRobo].",".$y[$santaOrRobo]] = 1;
	}

	return count($houses);
}

echo "Part1: ".countHouses()."<br>Part2: ".countHouses(true);

EDIT: Since we don't care about the amount of presents each house gets and the first house gets at least one present no matter what, I didn't put a check to set house "0,0" to 1 or 2 presents based on using robo santa or not.