使用JavaScript对用户响应进行评级(比较两个数组)

Ale*_*lex 6 javascript arrays diff

我正在编写一个脚本,通过比较两个数组来评估用户响应.(这是一个测验,看看他们对单词逐字逐句了解的信息.)我已经有了一些我需要的代码,比如将用户响应小写并拆分.我只需要找到差异/错误的数量.例如:

var correctanswer = ["The","quick","brown","fox","jumped","over","the","lazy","dog"];
var useranswer = ["The","brown","fox","jumped","up","and","over","the","really","lazy","cat"];
alert(counterrors(correctanswer, useranswer));
Run Code Online (Sandbox Code Playgroud)

在这个特殊的例子,运行我正在寻找的函数将返回用户做出5个错误(他们省略 "快",补充 "上升","和",和"真",而改为 "狗"到"猫").如您所见,两个阵列的长度可能不同.

有人知道如何处理这个问题吗?我在想它可能是一个循环:

for (x in correctanswer) {
    // compare correctanswer[x] to useranswer[x]... not sure how exactly. Seems tricky...
}
Run Code Online (Sandbox Code Playgroud)

谢谢你看这个!我见过John Resig的差异解决方案(http://ejohn.org/projects/javascript-diff-algorithm/)和其他类似的东西,甚至是一些数组比较,但似乎没有任何工作,因为我找到的回归所有差异,而我想知道有多少差异.再次,感谢您的关注,请让我知道任何问题.

更新:非常感谢Magnar的答案!它工作得很好.

Mag*_*nar 6

你所追求的是两个阵列的Levenshtein距离.

它是一种算法,用于计算将一个序列转换为另一个序列所需的添加,删除替换的数量.

我链接维基百科页面有一个伪代码实现.我为您完成了JavaScript的逐行转换:

var correctanswer = ["The","quick","brown","fox","jumped","over","the","lazy","dog"];
var useranswer =    ["The","brown","fox","jumped","up","and","over","the","really","lazy","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];
}
Run Code Online (Sandbox Code Playgroud)

这将登录5到控制台.正如您将看到的那样,阵列之间的距离正确.学生没有添加lazy.所以它是1个删除,3个添加和1个替换.