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 KikiStars1976
"use strict";
var findDistance = (function() {
var matrixs = [[-1,-1], [-1, 1], [ 1, 1],[ 1, -1]];
var matrixd = [[ 0, 1], [ 1, 0], [ 0,-1],[-1, 0]];
return function (first, second) {
var pf = calculatepos(first);
var ps = calculatepos(second);
return Math.abs(pf[0] - ps[0]) + Math.abs(pf[1] - ps[1]);
function calculatepos(number) {
if (number <= 1) {
return [0, 0];
}
var lap = Math.ceil((Math.sqrt(number) - 1) / 2);
var lc = number - Math.pow(lap * 2 - 1, 2);
var ld = Math.floor((lc - 1) / lap / 2);
var lm = lc - ld * lap * 2;
return [matrixs[ld][0] * lap + lm * matrixd[ld][0],
matrixs[ld][1] * lap + lm * matrixd[ld][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, 16), 10, "6th example");
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
Nov. 30, 2016