[英]More efficient way to compute cooccurrence
我想形象化人與人之間的關系網絡。
我的數據如下所示:
let networkData = [
["John","Dylan","Brian"],
["Dylan","Brian"],
];
我想要這樣的輸出:
let networkMatrix.links = [
{source: "John", target: "Dylan", weight: 1},
{source: "John", target: "Brian", weight: 1},
{source: "Brian", target: "Dylan", weight: 2}
];
約翰和布萊恩共享一組,所以他們的權重為1。約翰和迪倫也是如此。 由於Dylan和Brian分成兩組,他們的關系權重為2。
現在,這里是我認為需要幫助的地方。 我這樣做的方法是遍歷networkData
每一行,然后遍歷數組的每個元素。 對於每個元素,請遍歷之后的所有元素,並在networkMatrix
增加其得分。 這是我的代碼。
var i = 0, j = 0;
networkData.map(function(d) {
d.forEach(function(val, ind, tab) {
for (let k = ind + 1; k < tab.length; k++) {
while ((i = networkMatrix.person1.indexOf(val, i + 1)) != -1) {
while ((j = networkMatrix.person2.indexOf(tab[k], j + 1)) != -1) {
if (i === j) {
networkMatrix.score[i]++;
}
}
}
}
})
});
這是一個jsfiddle: https ://jsfiddle.net/0t81jg3b/2/
如您所見,它甚至在jsfiddle上也不起作用。 但是它或多或少在我的計算機上工作,我不知道為什么:
如果對於這樣一個簡單的任務來說,這樣變得太復雜了,有人可以給我一些如何擺脫困境的指示嗎?
您可以按照以下步驟進行操作:
Map
,否則可以使用普通對象 const groupes = [ ["John", "Dylan", "Brian"], ["Dylan", "Brian"], ["John", "Kate"] ], // Get unique list of names names = [...new Set([].concat(...groupes))], // Create a 2D-map with a counter set to zero map = new Map(names.map(name => [name, new Map(names.map(name2 => [name2, 0]))])), result = []; // Count the pairs for (const groupe of groupes) { for (const source of groupe) { const targetMap = map.get(source); for (const target of groupe) { if (source < target) targetMap.set(target, targetMap.get(target)+1); } } } // Convert nested maps to result structure for (const [source, targetMap] of map.entries()) { for (const [target, weight] of targetMap.entries()) { if (weight) result.push({source, target, weight}); } } console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.