计算for循环后字符串的出现次数

时间:2016-01-05 22:14:41

标签: javascript loops for-loop

我正在使用Javascript开展个人项目。我处于中间层面。 我创建了一个for循环,它给出了一个随机数列表。对于每个" i",有一对整数。整数总是正的,不同的并且在一定范围内(例如1到10之间)。 让我们说,在我运行循环后,我得到了这个:

1 vs 3
4 vs 7
5 vs 8
2 vs 3
7 vs 5
3 vs 4
1 vs 2
3 vs 5
3 vs 1
5 vs 7
... and so on...

现在,我如何计算每对出现的发生次数。例如,我希望能够:

3 vs 1: occurred 2 times
7 vs 5: occurred 2 times
3 vs 5: occurred 1 time

And so on...

顺序没关系,所以我认为3 vs 1和1 vs 3是相同的。我意识到这可能会使事情复杂化。

1 个答案:

答案 0 :(得分:0)

// Generate Pairs
var randomPairs = []
for (var i = 0; i < 10; ++i) {
  var randomPair = [Math.floor(Math.random() * 4) + 1, Math.floor(Math.random() * 4) + 1]
  randomPairs.push(randomPair)
}

// Count Pairs
var randomPairsCounted = []
for (var i = 0; i < randomPairs.length; ++i) {
  var a = randomPairs[i][0]
  var b = randomPairs[i][1]
  if (a > b) {
    var t = a
    a = b
    b = t
  }
  var doublicate = false
  for (var j = 0; j < randomPairsCounted.length; ++j) {
    if (randomPairsCounted[j][0] == a && randomPairsCounted[j][1] == b) {
      randomPairsCounted[j][2]++
      doublicate = true
      break
    }
  }
  if (doublicate == false) {
    randomPairsCounted.push([a, b, 1])
  }
}

// Demo Output
document.write("Pairs: " + JSON.stringify(randomPairs) + "<br><br>")
for (var i = 0; i < randomPairsCounted.length; ++i) {
  document.write(randomPairsCounted[i][0] + " vs " + randomPairsCounted[i][1] + 
                 ": occured " + randomPairsCounted[i][2] + " time" + 
                 (randomPairsCounted[i][2] == 1 ? "" : "s") + "<br>")
}