Last active
December 6, 2015 20:19
-
-
Save Gregoor/730a3ae1ccb6ef2fef2b to your computer and use it in GitHub Desktop.
Advent of Code - Day 3: Perfectly Spherical Houses in a Vacuum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parseSantaRoute = (str, roboMode = false) => { | |
const charFns = { | |
'^': (x, y) => [x , y + 1], | |
'v': (x, y) => [x , y - 1], | |
'>': (x, y) => [x + 1, y ], | |
'<': (x, y) => [x - 1, y ] | |
}; | |
let error; | |
let position = [0, 0]; | |
let roboPosition = [0, 0]; | |
let santasMove = true; | |
let visitedHouses = new Map(); | |
visitedHouses.set(position.toString(), true); | |
for (let i = 0; i < str.length; i++) { | |
const char = str[i]; | |
const fn = charFns[char]; | |
if (!fn) { | |
error = `Invalid character ${char} at position ${i + 1}`; | |
break; | |
} | |
let newPosition; | |
if (!roboMode || santasMove) { | |
santasMove = false; | |
newPosition = position = fn(...position); | |
} else { | |
santasMove = true; | |
newPosition = roboPosition = fn(...roboPosition); | |
} | |
visitedHouses.set(newPosition.toString(), true); | |
} | |
return error ? {error} : {visitedHouses: visitedHouses.size}; | |
}; | |
const expect = (actual, expected) => { | |
if (actual !== expected) { | |
console.error(`Expected ${expected} got ${actual}`); | |
return false; | |
} | |
return true; | |
} | |
console.clear() | |
const tests = [ | |
...[ | |
['>', 2], | |
['^>v<', 4] | |
].map(([str, expected]) => { | |
return expect(parseSantaRoute(str).visitedHouses, expected); | |
}), | |
...[ | |
['^v', 3], | |
['^>v<', 3], | |
['^v^v^v^v^v', 11] | |
].map(([str, expected]) => { | |
return expect(parseSantaRoute(str, true).visitedHouses, expected); | |
}) | |
]; | |
if (tests.every(Boolean)) console.log('All tests passed!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment