0

I wanna write a function that receive two parameter that first one is an array and the second is an integer; So I wanna return two element of the array that their sum be equal the second function's parameter. For example in this case findSum([1,2,3,5], 5) my function will return 2 and 3 that their sum being 5. I wrote a function but I think it can be better with another optimized coding.

function findSum(arr, sum){
  for(element of arr) {
    const first_element = element;
    for(innerElement of arr){
      if((innerElement !== first_element) && (innerElement + element === sum) )
          return {first_element, innerElement}
    }
  }
}
N.SH
  • 616
  • 7
  • 20

1 Answers1

3

So, one clear issue with your code is that findSum([2,2,3],4) won't work, because of this line: if((innerElement !== first_element). You should check indexes, rather than values to avoid this.

Very quick example:

findSum = (arr, sum) => {
        return arr.map((x, i) => {
            return arr.map((y, j) => {
                if(i === j) return null;
                return x + y === sum ? {x, y} : null;
            }).filter(x => x);
        }).flat()[0];
    }

Essentially, what I''m doing is very similar to your original version, with some slight tweaks.

Rather than using two for loops like you, I use two maps to iterate over the array. This gives me access to the index (i & j).

If i === j then it's the exact same element (and not just the same value) so we can ignore it. This solves the if((innerElement !== first_element) issue.

Then I check to see if the sum is correct and return the values, or null if it's incorrect. Filtering this array with filter(x => x) returns only the truthy elements, i.e. removes the nulls so we are left with all the matches.

We then flatten the array and return the first object as that's all we need, but we could change that to return all the matches. findSum([2,2,1,3], 4) has two matches for example.

Key concepts: Array.map Array.filter Array.flat

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
  • Yes thanks for your debugging your idea is true @Harry – N.SH Nov 24 '21 at 10:20
  • Perhaps you could explain a bit better what you are doing and add references to MDN what `map` `flat` and `filter` are ;) – Thomas Junk Nov 24 '21 at 10:21
  • @ThomasJunk no idea how you got that link working, but thanks. Literally does not work for me. If I go to edit, don't make any changes (or even touch the box in anyway) and try and save this edit I get this error: "Your post appears to contain code that is not properly formatted as code. Please indent all code by 4 spaces using the code toolbar button or the CTRL+K keyboard shortcut. For more editing help, click the [?] toolbar icon." Bizarre and unusable. Time to leave. –  Nov 24 '21 at 10:47
  • Great answer, upvoted! Still, since optimization was asked for, a standard C-style double loop might also be considered. It seems to be faster even for simple iterations (see https://stackoverflow.com/a/30834687) while in this case only the relevant *n*(n-1)/2* pairs are walked through. – kikon Nov 24 '21 at 10:55
  • 1
    @Harry thank you again for your clear explanation I exactly wanted a clear and optimized code for my question that you answered me – N.SH Nov 24 '21 at 10:59