Last active
October 23, 2023 19:00
-
-
Save KristofferK/728604bad7470319f341034ad0a8337d to your computer and use it in GitHub Desktop.
Calculate the euclidean distance using TypeScript. Supports N dimensions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const calculateDistance = (p: number[], q: number[]) => { | |
if (p.length != q.length) return -1; | |
const subtracted = q.map((i, n) => i - p[n]); | |
const powered = subtracted.map(e => Math.pow(e, 2)); | |
const sum = powered.reduce((total, current) => total + current, 0) | |
return Math.sqrt(sum); | |
} | |
// Three dimension | |
const p = [2.15, 16.5, 5.6]; | |
const q = [5.3, 1.2, 10.5]; | |
console.log(calculateDistance(p, q)); // 16.371392732446438 | |
// Six dimension | |
const p2 = [2.15, 16.5, 5.6, 18.9, 11.4, 9.1]; | |
const q2 = [5.3, 1.2, 10.5, 18.9, 0, 10]; | |
console.log(calculateDistance(p2, q2)); // 19.969789683419304 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment