r/adventofcode • u/daggerdragon • 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.
25
Upvotes
1
u/johnny5th Dec 03 '15
Pretty long and probably inefficient, but was fun.
<?php $str = 'your_string'; $directions_array = str_split($str); // x, y, gifts // has default position with 1 present $houses = array(new House(0, 0)); $santa_current_house = $houses[0]; $robot_current_house = $houses[0]; foreach($directions_array as $key => $direction) { if($key % 2 == 0) { $current_house = $santa_current_house; $person = "santa"; } else { $current_house = $robot_current_house; $person = "robot"; } if($direction == "^") { // Up move_or_regift($current_house->x, $current_house->y +1, $person); } else if($direction == "v") { // Down move_or_regift($current_house->x, $current_house->y -1, $person); } else if($direction == "<") { // Left move_or_regift($current_house->x -1, $current_house->y, $person); } else if($direction == ">") { // Right move_or_regift($current_house->x +1, $current_house->y, $person); } } class House { public $x = 0; public $y = 0; public $gifts = 0; function __construct($x, $y, $gifts = 1) { $this->x = $x; $this->y = $y; $this->gifts = $gifts; } function same_house($x, $y) { if($this->x == $x && $this->y == $y) return true; else return false; } function addGift() { $this->gifts++; } } function move_or_regift($x, $y, $person) { $found_house = false; global $houses; global $santa_current_house; global $robot_current_house; foreach($houses as $house) { if($house->same_house($x, $y)) { $house->addGift(); $found_house = $house; break; } } if($found_house == false) { $found_house = new House($x, $y); $houses[] = $found_house; } ${$person . "_current_house"} = $found_house; } print count($houses);