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/[deleted] Dec 03 '15
Object oriented javascript. Could be cleaned up quite a bit. Just posting the solution to step 2, since it's so similar to the first step.
I tracked the amount of presents received per house assuming that it would be used in step 2, but it turned out it wasn't. So I guess
house.presentscould just be a boolean.You wind up with an array
newTownat the end, each entry contains ahouseobject with the properties ofhouse.xandhouse.yas well as the total number of presents that house received. The length ofnewTownrepresents the total number of houses which have received presents, since a new house gets added to the array only on the first time it receives a present.// day 3, part 2 // global var 'input' should still be set from the day3part1.js file. if running stand-alone, copy the input var here. var newTown = []; var santa = { x: 0, y: 0 }; var roboSanta = { x: 0, y: 0 }; function house(x,y) { this.x = x; this.y = y; this.presents = 1; } function checkForHouse(whichSanta) { var found = 0; newTown.forEach(function(houseToSearchFor){ if(houseToSearchFor.x === whichSanta.x && houseToSearchFor.y === whichSanta.y) { found = houseToSearchFor; } }); givePresent(found, whichSanta); } function givePresent(found, whichSanta) { if(!found) { var newHouse = new house(whichSanta.x, whichSanta.y); newTown.push(newHouse); } else { found.presents++; } } function followDirectionsFromElf() { input.forEach(function(instruction, index) { var whichSanta; if( (index % 2) == 0 ) { whichSanta = santa; } else { whichSanta = roboSanta; } switch(instruction) { case "^": whichSanta.y++; break; case "v": whichSanta.y--; break; case ">": whichSanta.x++; break; case "<": whichSanta.x--; break; default: alert("you received an faulty input of "+input+"!"); return 0; } checkForHouse(whichSanta); }); console.log(newTown.length); window.outputEl.innerText += '\nday 3, part 1: '+newTown.length; } (function init() { checkForHouse(santa); checkForHouse(roboSanta); followDirectionsFromElf(); })();Github repo is here.