Skip to content

Instantly share code, notes, and snippets.

@rcombs
Created December 4, 2017 09:53
Show Gist options
  • Save rcombs/8e78839c2f8c1b0e9852bda8e67d93e9 to your computer and use it in GitHub Desktop.
Save rcombs/8e78839c2f8c1b0e9852bda8e67d93e9 to your computer and use it in GitHub Desktop.
var target = 368078;
var size = 20;
var arr = new Array(size);
for (var i = 0; i < size; i++) {
arr[i] = new Array(size);
arr[i].fill(0);
}
var offset
var zeroOffset = Math.floor(size / 2);
arr[zeroOffset][zeroOffset] = 1;
var hrstart = process.hrtime();;
var side = 0;
var posInSide = 0;
var posInLayer = 0;
var layer = 0;
var nextLayer = 2;
var sideLength = 1;
var val = 1;
var nextSide = 2;
var i;
for (i = 2; val <= target && i < (size - 2) * (size - 2); i++, posInSide++) {
if (i == nextLayer) {
layer++;
sideLength += 2;
nextLayer = sideLength * sideLength + 1;
posInLayer = 0;
side = -1;
}
if (i == nextSide) {
nextSide = i + (sideLength - 1);
posInSide = 0;
side++;
}
var coords = {x: zeroOffset, y: zeroOffset};
var mul = (side > 1) ? -1 : 1;
var dir = (side & 1);
var offset = (posInSide - (sideLength - 3) / 2);
if (dir == 0) {
coords.x += mul * layer;
coords.y += mul * offset;
} else {
coords.x -= mul * offset;
coords.y += mul * layer;
}
val = 0;
val += arr[coords.y + 1][coords.x + 1];
val += arr[coords.y + 1][coords.x ];
val += arr[coords.y + 1][coords.x - 1];
val += arr[coords.y ][coords.x - 1];
// val += arr[coords.y ][coords.x ];
val += arr[coords.y ][coords.x + 1];
val += arr[coords.y - 1][coords.x - 1];
val += arr[coords.y - 1][coords.x ];
val += arr[coords.y - 1][coords.x + 1];
arr[coords.y][coords.x] = val;
}
hrend = process.hrtime(hrstart);
console.log(val);
console.log("Execution time: %ds", hrend[0] + hrend[1]/1e9);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment