0

can anyone help me solve javascript Two Sum

Have the function TwoSum(arr) take the array of integers stored in arr, and determine if any two numbers (excluding the first element) in the array can sum up to the first element in the array. For example: if arr is [7, 3, 5, 2, -4, 8, 11], then there are actually two pairs that sum to the number 7: [5, 2] and [-4, 11]. Your program should return all pairs, with the numbers separated by a comma, in the order the first number appears in the array. Pairs should be separated by a space. So for the example above, your program would return: 5,2 -4,11 If there are no two numbers that sum to the first element in the array, return -1 Examples Input: [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7] Output: 6,11 10,7 15,2 Input: [7, 6, 4, 1, 7, -2, 3, 12] Output: 6,1 4,3

22nd Jun 2021, 2:14 AM
Khorommbi Nkhangweleni
Khorommbi Nkhangweleni - avatar
4 Respuestas
+ 2
function TwoSum(arr) { var sum=[]; for (var i=0;i<arr.length;i++){ for(var p=i+1;p<arr.length;p++){ if(arr[i]+arr[p]===arr[0]){ sum.push([arr[i],arr[p]]); } } // code goes here return sum; } } // keep this function call here console.log(TwoSum(readline()));
22nd Jun 2021, 3:24 AM
Eashan Morajkar
Eashan Morajkar - avatar
0
Khorommbi Nkhangweleni your TwoSum function requires two arguments but you're giving it only one.
22nd Jun 2021, 3:23 AM
Eashan Morajkar
Eashan Morajkar - avatar
- 3
Here is my codes function TwoSum(arr,S) { var sum=[]; for (var i=0;i<arr.length;i++){ for(var p=i+1;p<arr.length;p++){ if(arr[i]+arr[p]===S){ sum.push([arr[i],arr[p]]); } } // code goes here return arr; } } // keep this function call here console.log(TwoSum(readline()));
22nd Jun 2021, 2:28 AM
Khorommbi Nkhangweleni
Khorommbi Nkhangweleni - avatar