Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i implement functional loop statements instead of for loops in this case?

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???

like image 477
Saher Elgendy Avatar asked Jan 28 '26 13:01

Saher Elgendy


1 Answers

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

like image 127
Mulan Avatar answered Jan 31 '26 04:01

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!