阵列之间的对称差异 [英] symmetric difference between arrays
问题描述
我一直在编写代码,以使to或多个数组之间产生对称差异.如您所知,对称差异就是要排除两组数据中的元素.更多信息: https://en.wikipedia.org/wiki/Symmetric_difference
I have been writing the code to make a symmetric difference between to or more arrays. As you know, the symmetric difference is about excluding the elements which are in both sets of datas. More info: https://en.wikipedia.org/wiki/Symmetric_difference
这是我的代码:
//This function drops any repeated element from a vector
function unify(arr){
var result=arr.reduce(function(vector,num,index,self){
var len=self.filter(function (val){
return val===num;
}).length;
if (len>1){
var pos=self.indexOf(num);
self.splice(pos,1);
}
vector=self;
return vector;
},[]);
return result;
}
function sym(args) {
var arg = Array.prototype.slice.call(arguments);
var compact= arg.map(function(vector){
return unify(vector);
});
//We compare the vectors and delete any repeated element before we concat them
return compact.reduce(function(prev,next,index,self){
for (var key in next) {
var entry=next[key];
var pos=prev.indexOf(entry);
if (pos!==-1){
prev.splice(pos,1);
next.splice(key,1);
}
}
return prev.concat(next);
});
}
console.log(sym([1, 2, 3], [5, 2, 1, 4]));
我不明白我在做什么错.我期望得到[3,4,5]
的结果,但这不是我得到的结果.
I don't understand what am I doing wrong. I expected to get a result of [3,4,5]
but that is not the result I get.
推荐答案
进行拼接时,将更改数组的索引.因此它将跳过一些值.
When you do the splice, the indexing of the array is changed. So it would skip some values.
在您的示例中,为prev = [1,2,3]
和next = [5,2,1,4]
.
In your example, prev = [1,2,3]
and next = [5,2,1,4]
.
在第一个接头@ key = 1
之后,两个数组都看起来像这样prev = [1,3]
和next = [5,1,4]
.下一个键是2,它会跳过next
中的条目1
.由于存在接头,因此该索引向左移动了一个.
After the first splice @ key = 1
both arrays look like this prev = [1,3]
and next = [5,1,4]
. The next key is 2 which skips the entry 1
in next
. Because of the splice, this index has shifted one to the left.
我的解决方案(对不起,我在手机上,否则我会写代码)
My solutions (sorry, I'm on my phone else I'd have written code)
- 编写一个更深思熟虑的循环,并仅在必要时增加键. 因此,如果有接头,请不要增加,因为下一个可能 条目已移至当前键.
- 如果必须保持
for a in b
型循环,请考虑重复但恒定next
数组的参考
- Write a more deliberate loop, and increment key only when necessary. So if there's a splice, don't increment, because the would-be next entry has been shifted to the current key.
- If you must keep the
for a in b
-type loop, consider having a duplicate but constant reference for thenext
array
这篇关于阵列之间的对称差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!