Skip to content

Instantly share code, notes, and snippets.

@valeriecodes
Created January 19, 2018 18:52
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 valeriecodes/06acc1596b035bf13f139ed5a24705cf to your computer and use it in GitHub Desktop.
Save valeriecodes/06acc1596b035bf13f139ed5a24705cf to your computer and use it in GitHub Desktop.
All Tests Pass: Week 1
/**
* All Tests Pass: Week 1
* Given an array of integers, find out if any two items in the array add up to
* the target. For example, sumsToTarget([1,2], 3) should return true, but
* sumsToTarget([1,2], 4) should return false.
*/
function sumsToTarget(integers = [], target) {
return sumHelper(integers.sort(), target, 0, integers.length - 1);
}
function sumHelper(sortedArray, target, start, end) {
if (end <= start) {
// All possibilities are covered
return false;
} else {
// Sum beginning and end of search area
var sum = sortedArray[start] + sortedArray[end];
if (sum == target){
// Return true if sum is the target
return true;
} else if(sum >= target) {
// Eliminate largest number if sum is too big
return sumHelper(sortedArray, target, start, end - 1);
} else {
// Eliminate smallest number if sum is too small
return sumHelper(sortedArray, target, start + 1, end);
}
}
}
// Tests: Don't edit anything after this line.
assertEqual(sumsToTarget([1, 5, 3], 3), false, "Array [1, 5, 3] does not have items that add up to 3");
assertEqual(sumsToTarget([0, 2, 3, 5, 8], 3), true, "Array [0, 2, 3, 5, 8] has items that add up to 3");
assertEqual(sumsToTarget([5, 5], 5), false, "[5, 5] does not have items that add up to 5");
console.log("All clear 🎉");
function assertEqual(first, second, output) {
try {
if (first !== second) {
throw `${output} ${first} ${second}`
}
} catch (e) {
throw `${e} - ${output} ${first} ${second}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment