Created
December 4, 2017 14:47
-
-
Save hectorlorenzo/725863549c91411b9088950b2fdbc710 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 3
This file contains hidden or 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
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