Javascript Union Pairs Union Find

Ste*_*gwu 6 javascript graph-algorithm union-find

我正在寻找工会.我想根据其中一个索引是否与另一对索引共享一个数字来对数字对进行分组.所以:

我有一对像这样的对:

pairs: [[1,3], [6,8], [3,8], [2,7]]
Run Code Online (Sandbox Code Playgroud)

什么是在这样的工会中将它们分组的最佳方式:

[ [ 1, 3, 8, 6 ], [ 2, 7 ] ]
Run Code Online (Sandbox Code Playgroud)

([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 ] ]
Run Code Online (Sandbox Code Playgroud)

编辑 这是我目前使用的方法:

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)
}
Run Code Online (Sandbox Code Playgroud)

Dij*_*Dij 3

方法:

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)