kilojoules kilojoules - 15 days ago 5
Javascript Question

javascript find symmetric difference

My function needs to accept any number of lists, then output their symmetric difference.

sym([1, 2, 3], [5, 2, 1, 4])
should return
[3, 5, 4]
and
sym([1, 2, 5], [2, 3, 5], [3, 4, 5]) should return [1, 4, 5]
. I am confused by the result of my code - this returns an empty array.

function isin(num,arra)
{
for (var i=0; i<arra.length; i++)
{
if (num == arra[i])
{
return true;
}
}
return false;
}

function sym()
{
console.log("logging args");
console.log(arguments); // logs [Array[3], Array[4]]
var syms = [];
for (var i=0; i<arguments.length-1; i++)
{
var ins = false;
for (var j=0; j<arguments[i].length; j++)
{
for (var k=i+1; k < arguments.length; k++)
{
if(isin(arguments[i][j], arguments[k]))
{
ins = true;
}
}
}
if (ins === false)
{
syms.push(arguments[i][j]);
}
}
return syms;
}
sym([1, 2, 3], [5, 2, 1, 4]);

Answer

EDITED: to add some code Your loop variables are all global, including i. Put a var in front of them (at least before i) and you're done.

The following gets the symmetric difference of two sets. I hope you can get on from there.

function isin(num,arra)
{
  for (var i=0; i<arra.length; i++)
  {
    if (num == arra[i]){return true;}
  }
  return false;
}

function sym() 
{
   var j,k,i,l;
   var syms = [];
   for ( i=0; i<arguments.length; i++)
   {
     var ins = false;

     for (k=i+1; k < arguments.length; k++){
       for ( j=0; j<arguments[i].length; j++){
         if(!isin(arguments[i][j], arguments[k]))
         {
           syms.push(arguments[i][j]);
         }
       }
       for ( l=0; l<arguments[k].length; l++){
         if(!isin(arguments[k][l], arguments[i]))
         {
           syms.push(arguments[k][l]);
         }
       }
     }
   }
  return syms;
}
sym([1, 2, 3], [5, 2, 1, 4]);
Comments