gpt4 book ai didi

Javascript 联合对联合查找

转载 作者:数据小太阳 更新时间:2023-10-29 05:17:39 24 4
gpt4 key购买 nike

我致力于寻找工会。我想根据其中一个索引是否与另一对的索引共享一个数字来对数字对进行分组。所以:

我有一组这样的对:

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

最佳答案

方法:

finalArray = [], positions = {};    
for i to Array.length
for j=i+1 to Array.length
find match between arr[i] and arr[j]
if match found
pos = postion mapped to either i or j in positions
add elements of arr[i] or arr[j] or both depending on pos.
return finalArray

在该方法中,我们一直将要添加到 finalArray 的数组的位置存储在 positions 对象中,稍后我们可以使用该对象找到合适的位置,以将匹配数组的元素添加到 finalArray。

function mergeArrays(finalArray, pos, subArray) {
for (var k = 0; k < subArray.length; k++) {
if (finalArray[pos].indexOf(subArray[k]) < 0)
finalArray[pos].push(subArray[k]);
}

}

function unionArrays(arr) {
var finalArray = [arr[0]],
positions = {
0: 0
};
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
for (var k = 0; k < arr[i].length; k++) {
if (arr[j].indexOf(arr[i][k]) >= 0) {
if (i in positions) {
mergeArrays(finalArray, positions[i], arr[j]);
positions[j] = positions[i];
} else if (j in positions) {
mergeArrays(finalArray, positions[j], arr[i]);
positions[i] = positions[j];
} else {
var pos = finalArray.length;
finalArray.push([]);
mergeArrays(finalArray, pos, arr[i]);
mergeArrays(finalArray, pos, arr[j]);
positions[i] = positions[j] = pos;
}
break;
}

}
}
if (!(i in positions)) {
finalArray.push(arr[i]);
positions[i] = finalArray.length - 1;
}
}
return finalArray;
}
console.log(unionArrays([[1,3], [6,8], [3,8], [2,7]]));
console.log(unionArrays([[8,5], [10,8], [4,18], [20,12], [5,2], [17,2], [13,25],[29,12], [22,2], [17,11]]));

关于Javascript 联合对联合查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45315108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com