计算两个数组中所有可能的单词组合

时间:2012-04-23 11:36:49

标签: javascript jquery math

我想显示可能的唯一单词组合的总数。

这是我的示例代码:

var wordlist1 = ["Goldener", "Stählerner", "Purpurner", "Strahlender", "Elektrischer", "Taumelnder"];       
var wordlist2 = ["Indianer", "Ast", "Dachs", "Wolfshund", "Schäferhund", "Lupus", "Schakal"] ;

如何使用JS或Jquery实现此目的?

2 个答案:

答案 0 :(得分:1)

组合的数量是wordlist1.length * wordlist2.length

显示组合:

for (i = 0; i < wordlist1.length; i++)
  for (j = 0; j < wordlist2.length; j++){
    // do something like alert(wordlist1[i] + " " + wordlist2[j]);
    // or append the combinations somewhere
  }

答案 1 :(得分:1)

一个列表的示例...将for循环放在一个函数中你已经得到它了: - )

var wordlist1 = ["Goldener", "Stählerner", "Purpurner", "Strahlender", "Elektrischer", "Taumelnder"];
var wordlist2 = ["Indianer", "Ast", "Dachs", "Wolfshund", "Schäferhund", "Lupus", "Schakal"];

var uniqueWords = [];

for (var i = 0; i < wordlist1.length; i++) {
    var isUnique = true;

    for (var j = 0; j < uniqueWords.length; j++) { 
        if (wordlist1[i] == uniqueWords[j]) {
          isUnique = false;
          break;
        }
    }

    if (isUnique)
        uniqueWords.push(wordlist1[i]);
}

alert(uniqueWords.join("|"));