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

时间:2011-06-23 19:07:16

标签: 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));

在这个特定示例中,运行我正在寻找的功能会返回用户犯了5个错误(省略“快速”,添加“up”, “和”,“真的”,改变“狗”到“猫”)。如您所见,这两个数组的长度可能不同。

有人知道如何处理这个问题吗?我当时认为这可能是一个循环:

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

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

更新:非常感谢Magnar的回答!它运作得很好。

2 个答案:

答案 0 :(得分:6)

你所追求的是两个阵列的The Levenshtein Distance

这是一种计算将一个序列转换为另一个序列所需的添加删除替换的数量。

Wikipedia page I linked有一个伪代码实现。我已经为您完成了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];
}

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

答案 1 :(得分:0)

我不确定我是否完全明白你想要什么,但我认为这是解决方案。

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", "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));