Skip to content

Instantly share code, notes, and snippets.

@lonnen
Created December 21, 2010 20:47
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/750571 to your computer and use it in GitHub Desktop.
Save lonnen/750571 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.
function findClosest(items, value){
// a modified binary search that returns the last
// index checked, whether or not it had the correct value
var startIndex = 0;
var stopIndex = items.length - 1;
var middle = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
middle = Math.floor((stopIndex + startIndex)/2);
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
}
return middle;
}
function fasterThreeTuple( array, target ) {
if (isNaN(target)){return null;}
array.sort();
var j = 0;
var k = array.length - 1;
var i = 0;
while(k > j) {
i = findClosest(array, array[k]-array[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"];
print(set.sort());
for (var i = 0; i < testTargets.length; i++){
var result = crazyFast(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