Created
May 25, 2020 20:32
-
-
Save remi-bruguier/29a5ce009a33747b3ba74d2c92884b3b to your computer and use it in GitHub Desktop.
Given a list of numbers, find if there exists a pythagorean triplet in that list. A pythagorean triplet is 3 variables a, b, c where a² + b² = c²
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 findPythagoreanTriplets = (arr:number[]):boolean => { | |
if(arr.length<3) return false; | |
const sorted = arr | |
.map(v => v*v) | |
.sort((a,b) => a-b); | |
let [l,r,i] = [0, sorted.length -2, sorted.length -1]; | |
while(i>=2){ | |
if(sorted[l] + sorted[r] == sorted[i]){ | |
return true; | |
} | |
if(l==r){ | |
l = 0; | |
r--; | |
i--; | |
} | |
l++; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment