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:
xxxxxxxxxx
1
const calculateChebyshevDistance = (a, b) => {
2
if (a.length === 0 || a.length !== b.length) {
3
return NaN;
4
}
5
let max = Math.abs(a[0] - b[0]);
6
for (let i = 1; i < a.length; ++i) {
7
const distance = Math.abs(a[i] - b[i]);
8
if (distance > max) {
9
max = distance;
10
}
11
}
12
return max;
13
};
14
15
16
// Usage example:
17
18
const a = [2, 1];
19
const b = [3, 5];
20
21
const distance = calculateChebyshevDistance(a, b);
22
23
console.log(distance); // 4
In this section, you can find Chebyshev Distance examples for 3D and 4D.
xxxxxxxxxx
1
const calculateChebyshevDistance = (a, b) => {
2
if (a.length === 0 || a.length !== b.length) {
3
return NaN;
4
}
5
let max = Math.abs(a[0] - b[0]);
6
for (let i = 1; i < a.length; ++i) {
7
const distance = Math.abs(a[i] - b[i]);
8
if (distance > max) {
9
max = distance;
10
}
11
}
12
return max;
13
};
14
15
16
// Usage example:
17
18
const a1 = [1, 2, 3];
19
const b1 = [5, 5, 5];
20
21
const distance1 = calculateChebyshevDistance(a1, b1);
22
23
console.log(distance1); // 4
24
25
26
const a2 = [1, 2, 3, 4];
27
const b2 = [3, 4, 4, 3];
28
29
const distance2 = calculateChebyshevDistance(a2, b2);
30
31
console.log(distance2); // 2