Return whether any two sums to k

Return whether any two sums to k
0.0 0

#1

For example, given [3, 1, 3, 7] and k of 10, return true since 3 + 7 is 10

function toSum(nums, k){
    
    for(var i = 0; i < nums.length - 2; i++){
       for(var j = i + 1; j < nums.length - 1; j++){
           if(nums[j] + nums[i] === k){
               return true;
           }
           else 
                return false;
       }
    }
}

toSum([3, 1, 3, 7], 10);

what is an error…:thinking:


#2

You are experiencing an early return, because your for loop only checks the first two numbers (3 and 1) and then returns false. When a return statement is encountered, the function is immediately exited even if a loop has not completely iterated.


#3

thank you sir,
problem is solved :smile:


#4
function toSum(nums, k){
    var result = '';
    for(var i = 0; i < nums.length - 1; i++){
       for(var j = i + 1; j < nums.length; j++){
           if(nums[j] + nums[i] === k){
               return   'true';
           }
           else 
            result = 'false';
       }
    }
    return result;
}

toSum([5, 1, 3, 4], 2);

#5

What about?

function toSum(nums, k) {
	for (var i = 0; i < nums.length; i++) {
		for (var j = i + 1; j < nums.length; j++) {
			if (nums[j] + nums[i] === k) {
				return true;
			}
		}
	}
	return false;
}

#6

sir, you are right…:+1:t2:


#7

and use array.filter function when false or reduce when true?