Created
December 21, 2010 20:47
-
-
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.
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 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