Skip to content

Instantly share code, notes, and snippets.

@lonnen
Created December 20, 2010 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lonnen/748608 to your computer and use it in GitHub Desktop.
Save lonnen/748608 to your computer and use it in GitHub Desktop.
Searches for a triplet of values in an array that sum to the target value. Returns null if such a triplet doesn't exist. Takes O(n^2) time.
function threeTuple( array, target ) {
if (isNaN(target)){return null;}
array.sort();
for (var i = 0; i < array.length; i++) {
var j = i+1;
var k = array.length - 1; // start at the end of the array
while(k > j) {
summation = array[i] + array[j] + array[k];
if (summation === target) {return [i,j,k];}
if (summation > target) {k--;}
if (summation < target) {j++;}
}
}
return null;
}
// tests
var set = [0,1,2,3,-4,5];
var testTargets = [2, 4, 100, "100 million"]
for (var i = 0; i < testTargets.length; i++){
var result = threeTuple(set, testTargets[i]);
print((result === null) ? "No dice." : [set[result[0]],set[result[1]],set[result[2]]]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment