1

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]. How can I deal with the unknown number of arguments? I thought that I could use the single variable args to create a list of lists, but that isn't working.

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

function sym(args) {
   var syms = [];
   console.log(args);
   for (i=0; i<args.length; i++)
   {
     var ins = false;
     for (j=0; j<args[i].length; j++)
     {
       for (k=i+1; k < args.length; k++)
       {
         if(isin(args[i][j], args[k]))
         {
           ins = true;
         }
       }
     }
     if (ins === false)
     {
       syms.push(args[i][j]);
     }
   }
  return syms;
}
sym([1, 2, 3], [5, 2, 1, 4]);
kilojoules
  • 9,768
  • 18
  • 77
  • 149

4 Answers4

1

use arguments, not args

and you dont need to have it in the function definition.

(note: Im assuming the rest of your code works once you actually get what youre expecting passed in)

so:

function sym() {
   var syms = [];
   console.log(arguments);
   for (i=0; i<argumentss.length; i++)
   {
     var ins = false;
     for (j=0; j<arguments[i].length; j++)
     {
       for (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;
}
Rooster
  • 9,954
  • 8
  • 44
  • 71
1

For arrays with numbers:

function sym() {
  var temp = {}, res = [];

  for (var q=0; q<arguments.length; ++q) {
    for (var w=0; w<arguments[q].length; ++w) {
      temp[arguments[q][w]] ^= 1;
    }
  }

  for (var key in temp) {
    if (temp[key] === 1) {
      res.push(+key);
    }
  }

  return res;
}

console.log(sym([1, 2, 3], [5, 2, 1, 4]), sym([1, 2, 5], [2, 3, 5], [3, 4, 5]))
Qwertiy
  • 19,681
  • 15
  • 61
  • 128
1

Es6 introduces rest paramters. You can use it instead of arguments object.

function logAllArguments(...args) {
    for (var arg of args) {
        console.log(arg);
    }
}

logAllArguments(1,2,3)
blessanm86
  • 31,439
  • 14
  • 68
  • 79
0

Within in each function scope you have access to the arguments object . Any parameters you pass in will available inside of it. You can convert the arguments object to an array using Array.prototype.slice.apply(null,arguments) , and iterate over it.