Last active
January 25, 2023 02:17
-
-
Save beaugunderson/6638e74abc6aae1a7b3d25e97036d5d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const assert = require('assert'); | |
function fieldNumberToLetter(number) { | |
return String.fromCharCode(number + 65); | |
} | |
function squareToNeighbors(square) { | |
square = square.toUpperCase(); | |
const neighborMatrix = [ | |
[-1, +1], // NW | |
[0, +1], // N | |
[+1, +1], // NE | |
[-1, 0], // W | |
[0, 0], // Self | |
[+1, 0], // E | |
[-1, -1], // SW | |
[0, -1], // S | |
[+1, -1], // SE | |
]; | |
// RL90 | |
// ^^---- RL is the "field" | |
// ^^---- 90 is the "square" | |
const fieldX = square.charCodeAt(0) - 65; | |
const fieldY = square.charCodeAt(1) - 65; | |
const squareX = square.charCodeAt(2) - 48; | |
const squareY = square.charCodeAt(3) - 48; | |
const neighbors = []; | |
for (const [dx, dy] of neighborMatrix) { | |
let neighborFieldX = fieldX; | |
let neighborFieldY = fieldY; | |
let neighborSquareX = squareX + dx; | |
let neighborSquareY = squareY + dy; | |
if (neighborSquareX < 0) { | |
neighborSquareX += 10; | |
neighborFieldX -= 1; | |
} else if (neighborSquareX > 9) { | |
neighborSquareX -= 10; | |
neighborFieldX += 1; | |
} | |
if (neighborSquareY < 0) { | |
neighborSquareY += 10; | |
neighborFieldY -= 1; | |
} else if (neighborSquareY > 9) { | |
neighborSquareY -= 10; | |
neighborFieldY += 1; | |
} | |
if (neighborFieldX < 0) { | |
neighborFieldX += 18; | |
} else if (neighborFieldX > 17) { | |
neighborFieldX -= 18; | |
} | |
if (neighborFieldY < 0 || neighborFieldY > 17) { | |
continue; | |
} | |
const neighbor = `${fieldNumberToLetter(neighborFieldX)}${fieldNumberToLetter(neighborFieldY)}${neighborSquareX}${neighborSquareY}`; | |
neighbors.push(neighbor); | |
} | |
return neighbors; | |
} | |
function assertCorrect(neighbors, correct) { | |
for (let i = 0; i < neighbors.length; i++) { | |
assert.equal(neighbors[i], correct[i]); | |
} | |
} | |
console.log('RL90'); | |
assertCorrect( | |
squareToNeighbors('RL90'), | |
['RL81', 'RL91', 'AL01', 'RL80', 'RL90', 'AL00', 'RK89', 'RK99', 'AK09']); | |
console.log('RL00'); | |
assertCorrect( | |
squareToNeighbors('RL00'), | |
['QL91', 'RL01', 'RL11', 'QL90', 'RL00', 'RL10', 'QK99', 'RK09', 'RK19']); | |
console.log('AL00'); | |
assertCorrect( | |
squareToNeighbors('AL00'), | |
['RL91', 'AL01', 'AL11', 'RL90', 'AL00', 'AL10', 'RK99', 'AK09', 'AK19']); | |
console.log(squareToNeighbors('BR99')); | |
console.log(squareToNeighbors('BA00')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment