如何计算JavaScript中两个列表的相似度

时间:2016-02-19 11:10:04

标签: javascript list sorting

我有一个包含8个项目的主列表,然后是一些列表,其中包含与主列表相同的项目,但项目以不同的顺序显示。如何在每个列表与主列表之间找到百分比相似度?

例如,主列表可能是:

[8,7,6,5,4,3,2,1];

我想与之比较的一个列表可能是:

[8,6,4,2,7,5,3,1];

我知道我可以循环浏览主列表并检查匹配项,但有没有一种优雅的方法来计算列表中每个数字与主列表中相同数字的接近程度?

例如:

位置0:位置0的'8'匹配; 0个职位差异(100%) 位置1:位置4的'7'匹配; 3个职位差异(57.1%) 位置2:位置1的'6'匹配; 2个职位差异(71.4%)

最终结果将是两个列表之间的百分比相似度。

1 个答案:

答案 0 :(得分:1)

您可以使用数组mapreduce函数:

function getSimilaritry(a, b) {
  return a.map(function(val, index) { 
    //calculate the position offset and divide by the length to get each 
    //values similarity score
    var posOffset = Math.abs(b.indexOf(val) - index); 
    return posOffset/a.length
  }).reduce(function(curr, prev) {
    //divide the current value by the length and subtract from 
    //one to get the contribution to similarity 
    return (1 - curr/a.length) + prev;
  });
}

如果不保证列表具有相同的值,则需要为其添加处理。

另请注意,将参数ab传递给getSimilarity函数的顺序会影响结果。不清楚这是否适合您的申请。

PS:我认为你的问题是因为不包括你已经试图解决这个问题的代码而被拒绝了。

相关问题