FCC高级编程篇之Symmetric Difference

Symmetric Difference

Create a function that takes two or more arrays and returns an array of the symmetric difference (△ or ⊕) of the provided arrays.
Given two sets (for example set A = {1, 2, 3} and set B = {2, 3, 4}), the mathematical term "symmetric difference" of two sets is the set of elements which are in either of the two sets, but not in both (A △ B = C = {1, 4}). For every additional symmetric difference you take (say on a set D = {2, 3}), you should get the set with elements which are in either of the two the sets but not both (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}).
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:

对称差分是指某一元素仅存在于一个集合而不存在于另一个集合。

可类比于数组去重,两者有相似之处。数组去重判断数组中元素的下标与找到的第一个该元素的下标是否相等,而对称差分判断某元素在另一个集合中是否存在。

首先,函数参数可以有多个,因而得把参数合并为一个数组。

function sym(args) {
  let arr = Array.prototype.slice.call(arguments);

  return arr;
}

arguments是一个类似于数组的对象,但并非是数组,用Array.prototype.slice.call()方法将其转换为数组。

前面说了,对称差分和数组去重有类似之处,这里可以先进行合并,然后对合并后的数组进行过滤。

function sym(args) {
  let arr = Array.prototype.slice.call(arguments);

  return arr.reduce((arr1, arr2) => {
    return arr1.concat(arr2).filter((val) => {
      return arr1.indexOf(val) === -1 || arr2.indexOf(val) === -1;
    })
  });
}

但这还有个问题,如果一个数组中有重复的元素,那过滤后的数组中依然会重复,按照题意,去掉多余重复的元素。

function sym(args) {
  let arr = Array.prototype.slice.call(arguments);

  return arr.reduce((arr1, arr2) => {
    return arr1.concat(arr2).filter((val) => {
      return arr1.indexOf(val) === -1 || arr2.indexOf(val) === -1;
    }).filter((val, index, arr) => {
      return arr.indexOf(val) === index;
    });
  });
}

测试结果如下图所示。

Symmetric-Diffe测试结果图

posted @ 2017-11-05 16:02  月宫  阅读(521)  评论(0编辑  收藏  举报