diff --git a/src/algorithms/math/manhattan-distance/README.md b/src/algorithms/math/manhattan-distance/README.md new file mode 100644 index 0000000000..6fa1c09fb0 --- /dev/null +++ b/src/algorithms/math/manhattan-distance/README.md @@ -0,0 +1,9 @@ +This math algorithm is to calculate the manhattan distance with 4 variable key in by user + +Point 1 (x[i], y[i]) +Point 2 (x[j], y[j]) + +Then they will perform this calculation +(Math.abs(x[i] - x[j]) + Math.abs(y[i] - y[j])) + +To obtain the result diff --git a/src/algorithms/math/manhattan-distance/__test__/manhattanDistance.test.js b/src/algorithms/math/manhattan-distance/__test__/manhattanDistance.test.js new file mode 100644 index 0000000000..2b6ced3e37 --- /dev/null +++ b/src/algorithms/math/manhattan-distance/__test__/manhattanDistance.test.js @@ -0,0 +1,7 @@ +import manhattanDistance from '../manhattanDistance'; + +describe('manhattanDistance', () => { + it('should calculate the manhattan distance', () => { + expect(manhattanDistance(1,5,1,8)).toEqual(1); + }) +}) diff --git a/src/algorithms/math/manhattan-distance/manhattanDistance.js b/src/algorithms/math/manhattan-distance/manhattanDistance.js new file mode 100644 index 0000000000..3ff35cfc90 --- /dev/null +++ b/src/algorithms/math/manhattan-distance/manhattanDistance.js @@ -0,0 +1,19 @@ +//This function is calculate the manhattan distance +/** +* @param {string} x +* @param {string} y +* @return {string} +*/ +export default function manhattanDistance(x, y) { + +let SumOfManhattanDistance = 0; + +for (let i = 0; i < x.length; i++){ + for (let j = 0; j < x[i].length ; j++){ + //Compute the result of the Manhattan Distance + SumOfManhattanDistance += (Math.abs(x[i] - x[j]) + Math.abs(y[i] - y[j])); + } +} +//Send the result back to the main function +return SumOfManhattanDistance; +}