Languages
[Edit]
EN

JavaScript - Chebyshev Distance function

8 points
Created by:
Blythe-F
620

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

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:

    // 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

     

    See also

    1. JavaScript - Rectilinear Distance function

    2. JavaScript - how to calculate distance between two points with Pythagorean equation?

    References

    1. Chebyshev distance - Wikipedia

    Alternative titles

    1. JavaScript - Tchebychev distance function
    2. JavaScript - maximum metric function
    3. JavaScript - 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