Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] Square Spiral by Moff
function createSpiral(n) {
let size = 2 * n - 1;
let m = [];
for (let i = 0; i < size; i++)
m.push([]);
m[n - 1][n - 1] = 1;
for (let layer = 1; layer < n; layer++) {
let nums = [], di = (2 * layer - 1) ** 2 + 1;
for (let i = 0; i < 8 * layer; i++)
nums.push(i + di);
let sides = [];
for (let i = 0; i < nums.length; i += 2 * layer)
sides.push(nums.slice(i, i + 2 * layer));
for (let i = 0; i < 2 * layer; i++) {
m[n - layer - 1][n - layer + i] = sides[0][i];
m[n - layer + i][n + layer - 1] = sides[1][i];
m[n + layer - 1][n + layer - 2 - i] = sides[2][i];
m[n + layer - 2 - i][n - layer - 1] = sides[3][i];
}
}
return m;
}
function findPos(m, x) {
for (let i = 0; i < m.length; i++) {
let row = m[i];
for (let j = 0; j < row.length; j++) {
if (m[i][j] === x)
return [i, j];
}
}
}
function findDistance(first, second) {
let m = createSpiral(32);
let p1 = findPos(m, first), p2 = findPos(m, second);
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1]);
}
July 31, 2017