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 Sim0000
"use strict";
function coord(n) {
if(n == 1) return [0, 0]
ring = Math.floor((Math.sqrt(n - 1) - 1) / 2) + 1
w = n - (2 * ring - 1) * (2 * ring - 1) - 1
dir = Math.floor(w / (2 * ring))
step = w % (2 * ring)
switch(dir){
case 0: return [step - ring + 1, ring]
case 1: return [ring, ring - step - 1]
case 2: return [ring - step - 1, -ring]
case 3: return [-ring, step - ring + 1]
}
}
function findDistance(first, second) {
p1 = coord(first)
p2 = coord(second)
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1])
}
var assert = require('assert');
if (!global.is_checking) {
assert.equal(findDistance(1, 9), 2, "1st example");
assert.equal(findDistance(9, 1), 2, "2nd example");
assert.equal(findDistance(10, 25), 1, "3rd example");
assert.equal(findDistance(5, 9), 4, "4th example");
assert.equal(findDistance(26, 31), 5, "5th example");
// assert.equal(findDistance(50, 61), 10, "6th example");
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
July 8, 2016
Comments: