Skip to content

Instantly share code, notes, and snippets.

@humancatfood
Created December 18, 2017 14:49
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 humancatfood/e5d372ee8353135e95c1bc0986125eb1 to your computer and use it in GitHub Desktop.
Save humancatfood/e5d372ee8353135e95c1bc0986125eb1 to your computer and use it in GitHub Desktop.
Advent Of Code 2017 - 03(2) http://adventofcode.com/2017/day/3
// data spiral
// 147 142 133 122 59
// 304 5 4 2 57
// 330 10 1 1 54
// 351 11 23 25 26
// 362 747 806---> ...
function getStepsToData (target)
{
// a grid to keep track of the spiral
const grid = [[1]];
// helper to GET grid values (for convenience, yet undefined values default to 0)
const getEntry = (x, y) => grid[-y] && grid[-y][x] || 0;
// helper to SET grid values
const setEntry = (x, y, value) => {
if(!grid[-y])
{
grid[-y] = [];
}
grid[-y][x] = value;
};
// helper to get the sum of all adjacent cells
const sumNeighbours = (x, y) => [
getEntry(x-1, y-1),
getEntry(x, y-1),
getEntry(x+1, y-1),
getEntry(x-1, y),
getEntry(x+1, y),
getEntry(x-1, y+1),
getEntry(x, y+1),
getEntry(x+1, y+1)
].reduce((a, b) => a + b);
// helper function to print the spiral/grid for debugging
const printGrid = () => {
for (let y of Object.keys(grid).map(Number).sort((a, b) => a > b))
{
const row = Object.keys(grid[y]).map(Number).sort((a, b) => a > b).map(k => grid[y][k]);
console.log(row.join('\t'));
}
};
// same as in part one
const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];
let directionPointer = 0;
let x = 0;
let y = 0;
let stepsToNextCorner = 1;
let stepsTaken = 0;
let cornersTaken = 0;
let currentNumber = 0;
// build up the spiral until we reach the target
while (currentNumber < target)
{
x += directions[directionPointer][0];
y += directions[directionPointer][1];
// for each step we sum up the already existing neighbours
currentNumber = sumNeighbours(x, y);
// and store the result in its place in the spiral
setEntry(x, y, currentNumber);
// the rest is like in part one
stepsTaken += 1;
if (stepsTaken === stepsToNextCorner)
{
directionPointer = (directionPointer + 1) % directions.length;
stepsTaken = 0;
cornersTaken += 1;
if (cornersTaken % 2 === 0)
{
stepsToNextCorner += 1;
}
}
}
//printGrid();
return currentNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment