问题描述
|
我正在研究通过比较两个数组对用户响应进行评分的脚本。 (这是一个测验,看他们对单词的信息了解程度如何。)我已经有了一些所需的代码,例如使用户响应小写并拆分。我所需要的只是找到差异/错误数量的方法。例如:
var correctanswer = [\"The\",\"quick\",\"brown\",\"fox\",\"jumped\",\"over\",\"the\",\"lazy\",\"dog\"];
var useranswer = [\"The\",\"up\",\"and\",\"really\",\"cat\"];
alert(counterrors(correctanswer,useranswer));
在此特定示例中,运行我要查找的功能将返回用户犯了5个错误(它们省略了\“ quick \”,添加了\“ up \”,\“ and \”和\“ really \” ,并将\“ dog \\”更改为\\“ cat \”)。如您所见,两个数组的长度可能不同。
有人知道该如何处理吗?我以为这可能是一个循环,如:
for (x in correctanswer) {
// compare correctanswer[x] to useranswer[x]... not sure how exactly. Seems tricky...
}
感谢您的关注!我看过约翰·雷西格(John Resig)的差异解决方案(http://ejohn.org/projects/javascript-diff-algorithm/)和其他类似的东西,甚至还有一些数组比较,但是自从我发现那些以来,似乎没有任何效果返回所有差异,而我想看看有多少差异。再次感谢您的关注,如有任何问题,请通知我。
更新:非常感谢Magnar的回答!效果很好。
解决方法
您所追求的是两个数组的Levenshtein距离。
它是一种算法,计算将一个序列转换为另一个序列所需的添加,删除和取代的次数。
我链接的Wikipedia页面具有伪代码实现。我已经为您完成了JavaScript的逐行翻译:
var correctanswer = [\"The\",\"quick\",\"brown\",\"fox\",\"jumped\",\"over\",\"the\",\"lazy\",\"dog\"];
var useranswer = [\"The\",\"up\",\"and\",\"really\",\"cat\"];
console.log(calculate_levenshtein_distance(correctanswer,useranswer));
function calculate_levenshtein_distance(s,t) {
var m = s.length + 1,n = t.length + 1;
var i,j;
// for all i and j,d[i,j] will hold the Levenshtein distance between
// the first i words of s and the first j words of t;
// note that d has (m+1)x(n+1) values
var d = [];
for (i = 0; i < m; i++) {
d[i] = [i]; // the distance of any first array to an empty second array
}
for (j = 0; j < n; j++) {
d[0][j] = j; // the distance of any second array to an empty first array
}
for (j = 1; j < n; j++) {
for (i = 1; i < m; i++) {
if (s[i - 1] === t[j - 1]) {
d[i][j] = d[i-1][j-1]; // no operation required
} else {
d[i][j] = Math.min(
d[i - 1][j] + 1,// a deletion
d[i][j - 1] + 1,// an insertion
d[i - 1][j - 1] + 1 // a substitution
);
}
}
}
return d[m - 1][n - 1];
}
这将把“ 3”登录到控制台。如您所见,这是数组之间的正确距离。学生没有加lazy
。所以它是1个删除,3个添加和1个替换。
, 我不确定我是否完全了解您想要什么,但是我认为这是解决方案。
function counterrors(a,b) {
var max = Math.max(a.length,b.length);
var min = Math.min(a.length,b.length);
var count = 0;
for (var i = 0; i < min; i+=1) {
if (a[i] !== b[i]) {
count += 1;
}
}
return count + max - min; // max - min for any extra things that don\'t match
}
var correctanswer = [\"The\",\"dog\"];
var useranswer = [\"The\",\"cat\"];
alert(counterrors(correctanswer,useranswer));