Created
December 20, 2010 16:43
-
-
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.
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 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