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;
});
});
}

测试结果如下图所示。

最新文章

  1. CSS3动画属性Transform解读
  2. Quartz2D 编程指南(一)概览、图形上下文、路径、颜色与颜色空间
  3. The Template method pattern
  4. python视频教程大全集下载啦
  5. hdu 1034 (preprocess optimization, property of division to avoid if, decreasing order process) 分类: hdoj 2015-06-16 13:32 39人阅读 评论(0) 收藏
  6. poj 1651 http://poj.org/problem?id=1651
  7. Debug with jdb
  8. 使用MySQL
  9. 修改linux用户密码
  10. access 语句错误
  11. JavaScript 30 - 1 学习笔记
  12. Weave 如何与外网通信?- 每天5分钟玩转 Docker 容器技术(66)
  13. 利用模板template动态渲染jsp页面
  14. 【转】matlab针对不同格式文件的读写
  15. jq中的表单验证插件------jquery.validate
  16. centos7mini静默安装oracle11gr2
  17. 关于HTTP的笔记
  18. Gson使用技巧
  19. java 集合 Se HashTreeSet
  20. SSM项目的数据库密码加密方案

热门文章

  1. [ OS ][ Linux ] [ SA ] root 帳號名稱修改
  2. PHP学习过程中遇到的疑难杂症
  3. 通过adb 设置、删除、获取 系统配置值。
  4. 一些sass
  5. POJ 3517 And Then There Was One( 约瑟夫环模板 )
  6. Linux之awk使用
  7. axios统一拦截配置
  8. python学习(一):python基础
  9. 【hdu 6319】Ascending Rating
  10. 2015 Multi-University Training Contest 8 hdu 5390 tree