Skip to content

Instantly share code, notes, and snippets.

@ryanomor
Created April 23, 2018 00:12
Show Gist options
  • Save ryanomor/191b133650fa56097741187b71cc0a0b to your computer and use it in GitHub Desktop.
Save ryanomor/191b133650fa56097741187b71cc0a0b to your computer and use it in GitHub Desktop.
Find three numbers in an array that sum to the specified number
function findTriplets(arr, n) {
let idx2, idx3;
arr.sort((a, b) => a - b); // sort arr in ascending order
for(let i = 0; i < arr.length - 2; i++) {
idx2 = i + 1; // index of the first element in the remaining list of elementss
idx3 = arr.length - 1; // index of the last element
while(idx2 < idx3) {
if(arr[i] + arr[idx2] + arr[idx3] == n) {
console.log(`${arr[i]} + ${arr[idx2]} + ${arr[idx3]} equals ${n}`);
return true;
} else if (arr[i] + arr[idx2] + arr[idx3] < n) {
idx2++; // increment the second idx to a higher number
} else { // arr[i] + arr[idx2] + arr[idx3] > n
idx3--; //decrement the third idx to a lesser number
}
}
}
return false;
}
findTriplets([1, 4, 45, 6, 10, 8], 24);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment