-2
This pairSum algorithm should find if the sum of any two items in an array arr is equal to a given number target:
function pairSum(arr, target){
for (var i=0; i<arr.length;){
for (var j = arr.length-1; j>i;){
if (i=j) {return false} else {
if (arr[i] + arr[j] === target){ //we have our case
return true;
} else if (arr[i]+arr[j] < target) { //we don't have our case, but we know the last item (right index = j) needs to stay on the calculation, so we only change i
i++;
} else {
j--; //we still don't have our case, but we know the last item (right index = j) is not part of the solution, so we skip it to the left, and we keep the left item (index = i)
}
};
};
};
return false;
};
//invocation // current result // desired result
console.log( pairSum( [3,4,6,8,9,11], 14) ); //false // true because 11+3=14
console.log( pairSum( [3,4,6,8,9,11], 8) ); //false // false
console.log( pairSum( [3,4,4,8,9,11], 8) ); //false // true because 4+4=8
console.log( pairSum( [3,4,6,8,9,11], 16) ); //false // false
console.log( pairSum( [3,4,6,8,9,11], 20) ); //false // true because 11+9=20
And where is the question?
– Molx
Just looking up, you forgot one
=
hereif (i=j)
and thefor
'are incomplete because they lacki++
andj--
– msm.oliveira