EN
JavaScript - Chebyshev Distance function
8
points
In this short article, we would like to show how to calculate Chebyshev Distance using JavaScript.
The universal distance formula is: Where:
|
The two-dimensional formula is: The three-dimensional formula is: |
In simple words: Chebyshev Distance is the maximal positive distance between corresponding coordinates.
Chebyshev Distance has applications in different fields, e.g. Artificial Intelligence.
A practical example in 2D:
// ONLINE-RUNNER:browser;
const calculateChebyshevDistance = (a, b) => {
if (a.length === 0 || a.length !== b.length) {
return NaN;
}
let max = Math.abs(a[0] - b[0]);
for (let i = 1; i < a.length; ++i) {
const distance = Math.abs(a[i] - b[i]);
if (distance > max) {
max = distance;
}
}
return max;
};
// Usage example:
const a = [2, 1];
const b = [3, 5];
const distance = calculateChebyshevDistance(a, b);
console.log(distance); // 4
More complicated examples
In this section, you can find Chebyshev Distance examples for 3D and 4D.
// ONLINE-RUNNER:browser;
const calculateChebyshevDistance = (a, b) => {
if (a.length === 0 || a.length !== b.length) {
return NaN;
}
let max = Math.abs(a[0] - b[0]);
for (let i = 1; i < a.length; ++i) {
const distance = Math.abs(a[i] - b[i]);
if (distance > max) {
max = distance;
}
}
return max;
};
// Usage example:
const a1 = [1, 2, 3];
const b1 = [5, 5, 5];
const distance1 = calculateChebyshevDistance(a1, b1);
console.log(distance1); // 4
const a2 = [1, 2, 3, 4];
const b2 = [3, 4, 4, 3];
const distance2 = calculateChebyshevDistance(a2, b2);
console.log(distance2); // 2