Home > other >  Sum of 2 elements in array - Algorithm - JavaScript
Sum of 2 elements in array - Algorithm - JavaScript

Time:02-17

I'm working on JavaScript algorithms and could use some help. What am I doing wrong exactly?

// Given an array of arr, positive integers, and another number X.

// Determine whether or not there exist two elements in arr whose sum is exactly X.

function keyPair(arr, x){
    var sum=false;
    var key=0;
    var temp=0;
    for(var i=0;i<=arr.length;i  ){
        while(sum=false){
            key=arr[i];
            arr[i]=temp;
            temp=key;
        }
        if(temp arr[i]==x){
            sum=true;
        }
    }
    console.log(sum);
}
keyPair([1,2,4,3,6], 4);

CodePudding user response:

I think this one deserves an explanation:

sum=false is an assignment statement. As an expression, an assignment statement is evaluated as undefined (regardless of the value assigned). So while(sum=false) is actually while(undefined), which is interpreted as while(false).

CodePudding user response:

Your mistake was - as explained multiple times - the wrong comparison operator. I took the liberty of rewriting your code involving a .reduce() call:

function keyPair(arr,sum){
 return arr.reduce((a,c,j)=>{
  let i=arr.indexOf(sum-c);
  if (i>-1 && j<i) a.push([c,arr[i]]);
  return a;}, []);
}
console.log(keyPair([1,2,4,3,6], 5));

CodePudding user response:

first off, you might want to start by considering changing while(sum=false) to (sum===false), although running on vs code- it does run regardless.

  • Related