From 342382932d275ae0b2ea33bec58cc8a1a71ecdea Mon Sep 17 00:00:00 2001 From: Kausthub Kannan Date: Thu, 5 Oct 2023 15:31:48 +0530 Subject: [PATCH] feat: Added Euclidean Distance (#1418) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added Euclidean Distance * Added documentation to params * Use @see annotation --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com> --- Maths/EuclideanDistance.js | 19 +++++++++++++++++++ Maths/test/EuclideanDistance.test.js | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 Maths/EuclideanDistance.js create mode 100644 Maths/test/EuclideanDistance.test.js diff --git a/Maths/EuclideanDistance.js b/Maths/EuclideanDistance.js new file mode 100644 index 000000000..0cded84eb --- /dev/null +++ b/Maths/EuclideanDistance.js @@ -0,0 +1,19 @@ +/** + * @see [Wikipedia](https://en.wikipedia.org/wiki/Euclidean_distance) + * Calculate the Euclidean distance between two vectors. + * @param {number[]} vector1 - The first vector. + * @param {number[]} vector2 - The second vector. + * @returns {number} The Euclidean distance between the two vectors. + */ + +const EuclideanDistance = (vector1, vector2) => { + let sumOfSquares = 0 + + for (let i = 0; i < vector1.length; i++) { + sumOfSquares += Math.pow(vector1[i] - vector2[i], 2) + } + + return Math.sqrt(sumOfSquares) +} + +export { EuclideanDistance } diff --git a/Maths/test/EuclideanDistance.test.js b/Maths/test/EuclideanDistance.test.js new file mode 100644 index 000000000..d73bb0387 --- /dev/null +++ b/Maths/test/EuclideanDistance.test.js @@ -0,0 +1,19 @@ +import { EuclideanDistance } from '../EuclideanDistance.js' + +describe('EuclideanDistance', () => { + it('should calculate the distance correctly for 2D vectors', () => { + expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(2.8284271247461903, 10) + }) + + it('should calculate the distance correctly for 3D vectors', () => { + expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(3.4641016151377544, 10) + }) + + it('should calculate the distance correctly for 4D vectors', () => { + expect(EuclideanDistance([1, 2, 3, 4], [5, 6, 7, 8])).toBeCloseTo(8.0, 10) + }) + + it('should calculate the distance correctly for different 2D vectors', () => { + expect(EuclideanDistance([1, 2], [4, 6])).toBeCloseTo(5.0, 10) + }) +})