Javascript 将邻接列表转换为无向图的链接的有效方法

Javascript 将邻接列表转换为无向图的链接的有效方法,javascript,data-structures,graph,Javascript,Data Structures,Graph,我有一个邻接列表,如下所示: const list = [ [1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8], // ... ]; 我需要为没有重复项的无向图创建一组链接(下面的示例)。 像[0,1]和[1,0]这样的链接被认为是重复的 const links = [ [ 0, 1 ], // duplicates [ 0, 6 ], [ 0, 8 ], [ 1, 0 ], // duplicates [ 1, 4 ], // ...

我有一个邻接列表,如下所示:

const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];
我需要为没有重复项的无向图创建一组链接(下面的示例)。 像
[0,1]
[1,0]
这样的链接被认为是重复的

const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]
现在我这样做:

const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})

我想知道是否有更好的模式来解决大规模数组上的此类任务。

您可以对链接元组值进行排序,跳过检查
skip.indexOf(j)
并让
Set
处理重复项。

您可以将字符串数组作为集合的值,因为只有排序值的数组正在使用集合中的严格模式进行检查

const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]
基本数据类型(如字符串)效果最好

var list=[[1,6,8]、[0,4,6,9]、[4,6]、[4,5,8],
链接=新集合;
list.forEach((v,i)=>v.forEach(j=>links.add([Math.min(i,j),Math.max(i,j)].join());
log([…链接])

.as console wrapper{max height:100%!important;top:0;}
您可以使用一个对象来存储已使用的
值:index
,然后在添加到数组之前检查该对象

const list=[[1,6,8]、[0,4,6,9]、[4,6]、[4,5,8]、];
变量o={},r=[]
list.forEach(函数(e,i){
e、 forEach(函数(a){
如果(o[i]!=a){
r、 推送([i,a])
o[a]=i
}
})
})
console.log(JSON.stringify(r))