Skip to content

Commit 3423829

Browse files
feat: Added Euclidean Distance (TheAlgorithms#1418)
* Added Euclidean Distance * Added documentation to params * Use @see annotation --------- Co-authored-by: Lars Müller <[email protected]>
1 parent 96d122f commit 3423829

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Maths/EuclideanDistance.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @see [Wikipedia](https://en.wikipedia.org/wiki/Euclidean_distance)
3+
* Calculate the Euclidean distance between two vectors.
4+
* @param {number[]} vector1 - The first vector.
5+
* @param {number[]} vector2 - The second vector.
6+
* @returns {number} The Euclidean distance between the two vectors.
7+
*/
8+
9+
const EuclideanDistance = (vector1, vector2) => {
10+
let sumOfSquares = 0
11+
12+
for (let i = 0; i < vector1.length; i++) {
13+
sumOfSquares += Math.pow(vector1[i] - vector2[i], 2)
14+
}
15+
16+
return Math.sqrt(sumOfSquares)
17+
}
18+
19+
export { EuclideanDistance }

Maths/test/EuclideanDistance.test.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { EuclideanDistance } from '../EuclideanDistance.js'
2+
3+
describe('EuclideanDistance', () => {
4+
it('should calculate the distance correctly for 2D vectors', () => {
5+
expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(2.8284271247461903, 10)
6+
})
7+
8+
it('should calculate the distance correctly for 3D vectors', () => {
9+
expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(3.4641016151377544, 10)
10+
})
11+
12+
it('should calculate the distance correctly for 4D vectors', () => {
13+
expect(EuclideanDistance([1, 2, 3, 4], [5, 6, 7, 8])).toBeCloseTo(8.0, 10)
14+
})
15+
16+
it('should calculate the distance correctly for different 2D vectors', () => {
17+
expect(EuclideanDistance([1, 2], [4, 6])).toBeCloseTo(5.0, 10)
18+
})
19+
})

0 commit comments

Comments
 (0)