Skip to content

Instantly share code, notes, and snippets.

@hectorlorenzo
Created December 4, 2017 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hectorlorenzo/725863549c91411b9088950b2fdbc710 to your computer and use it in GitHub Desktop.
Save hectorlorenzo/725863549c91411b9088950b2fdbc710 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 3
function sum (x) {
var sum = 0;
while(x > 0) {
sum = sum + x;
x--;
}
return sum;
}
function getNumberBlock (number) {
return Math.ceil((Math.sqrt(number) - 1) / 2);
}
function getNumberPosition (number) {
if (number === 0) {
return {
x: 0,
y: 0
};
}
var blockIndex = getNumberBlock(number);
var blockLength = blockIndex * 2;
var initialBlockNumber = 8 * sum(blockIndex);
var x = -1 * blockIndex;
var y = -1 * blockIndex;
// we need to run this in 0-index mode
number = number - 1;
if (number >= (initialBlockNumber - blockLength) && number < initialBlockNumber) {
x = x + (initialBlockNumber - number);
}
initialBlockNumber = initialBlockNumber - blockLength;
if (number >= (initialBlockNumber - blockLength) && number < initialBlockNumber) {
y = y + (initialBlockNumber - number);
}
initialBlockNumber = initialBlockNumber - blockLength;
if (number >= (initialBlockNumber - blockLength) && number < initialBlockNumber) {
x = x + (initialBlockNumber - number);
y = Math.abs(y)
}
initialBlockNumber = initialBlockNumber - blockLength;
if (number >= (initialBlockNumber - blockLength) && number < initialBlockNumber) {
y = y + (initialBlockNumber - number);
x = Math.abs(x);
}
return {
x: x,
y: y
};
}
function getDistance (number) {
var coordinates = getNumberPosition(number);
return Math.abs(coordinates.x) + Math.abs(coordinates.y);
}
console.log(getDistance(289326));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment