Skip to content

Instantly share code, notes, and snippets.

@amwmedia
Created December 8, 2017 14:10
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 amwmedia/251c1939e65b1f5bdb122da787829f27 to your computer and use it in GitHub Desktop.
Save amwmedia/251c1939e65b1f5bdb122da787829f27 to your computer and use it in GitHub Desktop.
Advent Of Code 2017 - Day 3
function getDist(num) {
let sqrt = Math.ceil(Math.sqrt(num));
let sideLengthOfSq = (sqrt % 2 === 0 ? sqrt + 1 : sqrt);
let highestNumInSq = sideLengthOfSq * sideLengthOfSq;
let targetDistFromCorner = (highestNumInSq - num) % (sideLengthOfSq - 1);
let targetDistFromSideCenter = Math.abs(targetDistFromCorner - Math.floor(sideLengthOfSq/2));
const closestDistFromSq = (sideLengthOfSq - 1) / 2;
return closestDistFromSq + targetDistFromSideCenter;
}
function getFirstValueAbove(num) {
const grid = {0:{0:1}};
const getNum = (x, y) => (grid[x] || {})[y] || 0;
const setNum = (x, y, n) => {
grid[x] = grid[x] || {};
grid[x][y] = n;
return n;
};
const sumAroundPos = (x, y) => (
getNum(x, y-1) + getNum(x+1, y-1) + getNum(x-1, y-1)
+ getNum(x+1, y) + getNum(x-1, y)
+ getNum(x, y+1) + getNum(x+1, y+1) + getNum(x-1, y+1)
);
const calculateNextMove = (x, y) => {
const [north, south, east, west] = [[x, y+1], [x, y-1], [x+1, y], [x-1, y]];
const [n, s, e, w] = [north, south, east, west].map(([px, py]) => getNum(px, py));
if (n && !s && !e) { return east; }
if (!n && w && !e) { return north; }
if (!n && !w && s) { return west; }
if (!w && !s && e) { return south; }
};
let n = getNum(0, 0);
for(let x = 0, y = 0; n < num;) {
// decide what square is next in line
const [nextX, nextY] = calculateNextMove(x, y);
// calculate and fill square amount
n = setNum(nextX, nextY, sumAroundPos(nextX, nextY));
// set new current position to the new square
x = nextX; y = nextY;
}
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment