How to check if sum of any two elements in the array exists in the array using functional loop statements(map, forEach, reduce) instead of for loops.
For example an array like this
[1, 2, 9, 4, 3] // would return true as 1 + 2 = 3
[2,7,12,6,8,20] // true as 2 + 6 = 8 which is enough to make it true
[1, 2, 4, 9] //would return false
I can do this by for loops:
const checkSumExist = arr => {
for(let i = 0; i < arr.length; i++) {
for(let j = i + 1; j < arr.length; j++) {
if(arr.includes(arr[i] + arr[j])) return true;
}
}
return false;
}
So is there a solution using functional loop statement instead of nested for loops in this case???
A simplified implementation –
const main = (xs = []) =>
xs .some ((n, i) =>
xs .some ((m, j) =>
i < j && xs .includes (n + m)
)
)
console.log
( main ([ 1, 2, 4, 9, 4, 3 ]) // true
, main ([ 2, 7, 12, 6, 8, 20 ]) // true
, main ([ 1, 2, 4, 9 ]) // false
)
This optimization using Set improves speed to O(1) –
const main = (xs = [], s = new Set (xs)) =>
xs .some ((n, i) =>
xs .some ((m, j) =>
i < j && s .has (n + m)
)
)
console.log
( main ([ 1, 2, 4, 9, 4, 3 ]) // true
, main ([ 2, 7, 12, 6, 8, 20 ]) // true
, main ([ 1, 2, 4, 9 ]) // false
)
Remember only to optimize where necessary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With