Languages
[Edit]
EN

JavaScript - Rectilinear Distance function

10 points
Created by:
Wiktor-Sribiew
800

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

The universal distance formula is:

Where:

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

The two-dimensional formula is:

The three-dimensional formula is:

Rectilinear Distance is also known as taxicab metric, L1 distance or L1 norm, snake distance, city block distance, Manhattan distance, or Manhattan length.

It was used to measure the absolute distance needed to move from one place to the second one in taxicab city.

Rectilinear Dinstance calculation in JavaScript.
Rectilinear Dinstance calculation in JavaScript.

A practical example in 2D:

// ONLINE-RUNNER:browser;

const calculateRectilinearDistance = (a, b) => {
  	if (a.length === 0 || a.length !== b.length) {
      	return NaN;
    }
    let sum = 0.0;
    for (let i = 0; i < a.length; ++i) {
        sum += Math.abs(a[i] - b[i]);
    }
    return sum;
};


// Usage example:

const a = [1, 1];
const b = [4, 4];

const distance = calculateRectilinearDistance(a, b);

console.log(distance);  // 6

 

More complicated examples

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

// ONLINE-RUNNER:browser;

const calculateRectilinearDistance = (a, b) => {
  	if (a.length === 0 || a.length !== b.length) {
      	return NaN;
    }
    let sum = 0.0;
    for (let i = 0; i < a.length; ++i) {
        sum += Math.abs(a[i] - b[i]);
    }
    return sum;
};


// Usage example:


const a1 = [1, 2, 3];
const b1 = [5, 5, 5];

const distance1 = calculateRectilinearDistance(a1, b1);

console.log(distance1);  // 9


const a2 = [1, 2, 3, 4];
const b2 = [3, 4, 4, 3];

const distance2 = calculateRectilinearDistance(a2, b2);

console.log(distance2);  // 6

 

See also

  1. JavaScript - Chebyshev Distance function

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

References

  1. Rectilinear distance - Wikipedia
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