Skip to content

Instantly share code, notes, and snippets.

@devNoiseConsulting
Created January 3, 2018 03:14
Show Gist options
  • Select an option

  • Save devNoiseConsulting/8438c8ddae49950a58fe4f924aaf5823 to your computer and use it in GitHub Desktop.

Select an option

Save devNoiseConsulting/8438c8ddae49950a58fe4f924aaf5823 to your computer and use it in GitHub Desktop.
Spiral Memory - Advent of Code - 20171203
let findMoves = function(location) {
let previousSquare = Math.floor(Math.sqrt(location));
previousSquare = previousSquare % 2 == 0 ? previousSquare - 1 : previousSquare;
let sideSize = previousSquare + 1;
previousSquare *= previousSquare;
console.log('debug', previousSquare, Math.floor(sideSize / 2), Math.floor((location - previousSquare) % (sideSize / 2)));
return Math.floor(sideSize / 2) + Math.floor((location - previousSquare) % (sideSize / 2));
};
let test = 1;
let result = findMoves(test);
console.log(result);
test = 12;
result = findMoves(test);
console.log(result);
test = 23;
result = findMoves(test);
console.log(result);
test = 1024;
result = findMoves(test);
console.log(result);
test = 289326;
result = findMoves(test);
console.log(result);
let sumPoint = function(x, y, matrix) {
let sum = 0;
for (let i = x -1; i <= x + 1; i++) {
if (matrix[i]) {
for (let j = y -1; j <= y + 1; j++) {
//console.log('sumPoint', i, j)
if (matrix[i][j]) {
sum += matrix[i][j];
}
}
}
}
return sum;
};
let spiralExpand = function(location) {
let previousSquare = Math.floor(Math.sqrt(location));
previousSquare = previousSquare % 2 == 0 ? previousSquare - 1 : previousSquare;
let size = previousSquare + 1;
let length = Math.pow(size, 2);
let matrix = new Array(size).fill(0);
matrix = matrix.map(v => new Array(size).fill(0));
let x = 0; // current position; x
let y = 0; // current position; y
let d = 0; // current direction; 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
let c = 1; // counter
let s = 1; // chain size
let firstOver = -1;
// starting point
x = Math.floor(size / 2.0);
y = Math.floor(size / 2.0);
matrix[x][y] = 1;
for (let k = 1; k <= size - 1; k++) {
for (let j = 0; j < (k < size - 1 ? 2 : 3); j++) {
for (let i = 0; i < s; i++) {
matrix[x][y] = sumPoint(x, y, matrix);
if (firstOver < 0 && matrix[x][y] > location) {
firstOver = matrix[x][y];
i = s;
j = 4;
k = size;
}
switch (d) {
case 0:
y = y + 1;
break;
case 1:
x = x + 1;
break;
case 2:
y = y - 1;
break;
case 3:
x = x - 1;
break;
}
}
d = (d + 1) % 4;
}
s = s + 1;
}
return firstOver;
};
result = spiralExpand(test);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment