Skip to content

Instantly share code, notes, and snippets.

@tokdaniel
Last active September 9, 2020 22:00
Show Gist options
  • Save tokdaniel/06f056514c3af9560d0759034a7ace34 to your computer and use it in GitHub Desktop.
Save tokdaniel/06f056514c3af9560d0759034a7ace34 to your computer and use it in GitHub Desktop.
// How many steps a Knight takes on an infinite chessboard from O(0,0) to P (x,y)
// With O(1) time complexity
const knightsMetric = (x, y) => {
let normalizedX = Math.abs(x);
let normalizedY = Math.abs(y);
// Normailze coordinates, so that 0 <= y <= x
if(normalizedX < normalizedY) {
[normalizedY, normalizedX] = [normalizedX, normalizedY]
}
// Handle exceptions
if(normalizedX === 1 && normalizedY === 0) return 3
if(normalizedX === 2 && normalizedY === 2) return 4
const delta = normalizedX - normalizedY
if(delta < normalizedY) {
return delta + Math.floor((normalizedY - delta + 2) / 3) * 2;
} else {
const xbase = normalizedX - (normalizedY % 2) * 2;
return Math.floor(xbase / 4) * 2 + xbase % 4 + normalizedY % 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment