Languages
[Edit]
EN

TypeScript - Chebyshev Distance function

0 points
Created by:
cory
1786

In this short article, we would like to show how to calculate Chebyshev Distance using TypeScript.

The universal distance formula is:

Where:

  • x and y are points in the space,
  • i is a number of dimensions.

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:

    const calculateChebyshevDistance = (a: number[], b: number[]): number => {
        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: number[] = [2, 1];
    const b: number[] = [3, 5];
    
    const distance: number = calculateChebyshevDistance(a, b);
    
    console.log(distance); // 4

    Output:

    4

    More complicated examples

    In this section, you can find Chebyshev Distance examples for 3D and 4D.

    const calculateChebyshevDistance = (a: number[], b: number[]): number => {
        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: number[] = [1, 2, 3];
    const b1: number[] = [5, 5, 5];
    
    const distance1: number = calculateChebyshevDistance(a1, b1);
    
    console.log(distance1); // 4
    
    const a2: number[] = [1, 2, 3, 4];
    const b2: number[] = [3, 4, 4, 3];
    
    const distance2: number = calculateChebyshevDistance(a2, b2);
    
    console.log(distance2); // 2

    Output:

    4
    2

    See also

    1. JavaScript - Chebyshev Distance function

    References

    1. Chebyshev distance - Wikipedia

    Alternative titles

    1. TypeScript - Tchebychev distance function
    2. TypeScript - maximum metric function
    3. TypeScript - L infinity metric
    Donate to Dirask
    Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
    Join to our subscribers to be up to date with content, news and offers.
    Native Advertising
    🚀
    Get your tech brand or product in front of software developers.
    For more information Contact us
    Dirask - we help you to
    solve coding problems.
    Ask question.

    ❤️💻 🙂

    Join