EN
TypeScript - Chebyshev Distance function
0 points
In this short article, we would like to show how to calculate Chebyshev Distance using TypeScript.
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: number[], b: number[]): number => {
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: number[] = [2, 1];
19
const b: number[] = [3, 5];
20
21
const distance: number = calculateChebyshevDistance(a, b);
22
23
console.log(distance); // 4
Output:
xxxxxxxxxx
1
4
In this section, you can find Chebyshev Distance examples for 3D and 4D.
xxxxxxxxxx
1
const calculateChebyshevDistance = (a: number[], b: number[]): number => {
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: number[] = [1, 2, 3];
19
const b1: number[] = [5, 5, 5];
20
21
const distance1: number = calculateChebyshevDistance(a1, b1);
22
23
console.log(distance1); // 4
24
25
const a2: number[] = [1, 2, 3, 4];
26
const b2: number[] = [3, 4, 4, 3];
27
28
const distance2: number = calculateChebyshevDistance(a2, b2);
29
30
console.log(distance2); // 2
Output:
xxxxxxxxxx
1
4
2
2