我正在寻找工会。我想根据其中一个索引是否与另一对索引共享一个数字来对数字对进行分组。所以:
我有一系列对,例如:
pairs: [[1,3], [6,8], [3,8], [2,7]]
将它们分组到这样的工会中的最佳方法是什么:
[ [ 1, 3, 8, 6 ], [ 2, 7 ] ]
([1,3] 和 [3,8] 在一起,因为它们共享 3。该组与 [6,8] 联合,因为它们共享 8。在 javascript 中执行此操作的最佳方法是什么?
以下是其他示例:
pairs: [[8,5], [10,8], [4,18], [20,12], [5,2], [17,2], [13,25],[29,12], [22,2], [17,11]]
into [ [ 8, 5, 10, 2, 17, 22, 11 ],[ 4, 18 ],[ 20, 12, 29 ],[ 13, 25 ] ]
编辑 这是我目前使用的方法:
findUnions = function(pairs, unions){
if (!unions){
unions = [pairs[0]];
pairs.shift();
}else{
if(pairs.length){
unions.push(pairs[0])
pairs.shift()
}
}
if (!pairs.length){
return unions
}
unite = true
while (unite && pairs.length){
unite = false
loop1:
for (i in unions){
loop2:
var length = pairs.length;
for (j=0;j<length;j++){
if (unions[i].includes(pairs[j][0])){
if (!unions[i].includes(pairs[j][1])){
unions[i].push(pairs[j][1])
pairs.splice(j, 1)
j-=1;
length-=1
unite = true
}else{
pairs.splice(j, 1)
j-=1
length-=1
}
}else if (unions[i].includes(pairs[j][1])){
unions[i].push(pairs[j][0])
pairs.splice(j, 1)
unite = true
j-=1
length-=1
}
}
}
}
return findUnions(pairs, unions)
}