Monday, December 12, 2016

Recursion on Sorted Array

Find if any two elements in a sorted array can equal a sum.

Write a function checkSumOf2 that accepts two parameters, a sorted array and a number that is the target that two numbers in the array should sum to.
function checkSumOf2(ary, target) {
  function check2(ary, target, left, right) {
    if (left >= right) {
      return false;
    }
    var sum = ary[left] + ary[right];
    if (sum === target) {
      return true;
    } else if (sum > target) {
      right--;
    } else {
      left++;
    }
    return check2(ary, target, left, right);;
  }

  return check2(ary, target, 0, ary.length - 1);
}

console.log( '1.' + checkSumOf2([1,3,5,7], 8) )  // true
console.log( '2.' + checkSumOf2([0,2,6,8], 7) )  // false
console.log( '3.' + checkSumOf2([4,5,6,7], 12) ) // true
console.log( '4.' + checkSumOf2([1,2,3,4], 12) ) // false
console.log( '5.' + checkSumOf2([1,2,3,4], 4) )  // true