Created
February 8, 2017 06:16
-
-
Save ClayTaeto/566073dd82297afd9c36a88a7bdd7d08 to your computer and use it in GitHub Desktop.
Find the Triplets
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
function findTriplets(list){ | |
//TODO: assert list is array of numbers | |
//if there isn't enough items for a single result | |
if (!list.length && list.length < 3) { | |
return false; //throw? | |
} | |
list.sort(); | |
//set up dictionary of list for that sweet sweet constant time | |
var dict = {}; | |
for(let i of list){ | |
dict[i] = true; | |
} | |
var result = []; | |
var resultDict = {}; | |
var resultKey; | |
var target; | |
for(let i in list){ | |
for(let j = i + 1; j < list.length; j++){ | |
//These two checks could be combined, but I'd rather be overt and let uglify be succinct. | |
target = -(list[i] + list[j]) | |
if(!list[target]){ | |
continue; | |
} | |
//third number actually doesn't matter here since the list is sorted and it's value solved | |
resultKey = list[i] + " " + list[j] | |
if(resultDict[resultKey]){ | |
continue; | |
} | |
resultDict[resultKey] = true; | |
result.push([list[i], list[j], target]) | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment