amwmedia
12/8/2017 - 2:10 PM

Advent Of Code 2017 - Day 3

Advent Of Code 2017 - Day 3

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;
}
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;
}