Last active
March 4, 2018 16:21
-
-
Save io-developer/d8f99587a09dcbd4d078fa95542b80c2 to your computer and use it in GitHub Desktop.
AdventOfCode 2017 day 3-1
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
function calc(inputNum) { | |
var coord = spiralCoord(inputNum - 1); | |
return Math.abs(coord.x) + Math.abs(coord.y); | |
} | |
function spiralCoord(index) { | |
var coord = { x: 0, y: -1 }; | |
var dir = 3; | |
var vecs = { | |
0: { x: 1, y: 0 }, | |
1: { x: 0, y: -1 }, | |
2: { x: -1, y: 0 }, | |
3: { x: 0, y: 1 } | |
}; | |
for (var i = 0, step = 0, steps = 0; i <= index; i++) { | |
var v = vecs[dir]; | |
coord.x += v.x; | |
coord.y += v.y; | |
if (++step >= steps) { | |
step = 0; | |
dir = (dir + 1) % 4; | |
if (dir % 2 == 0) { | |
steps += 1; | |
} | |
} | |
} | |
return coord; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment