0

一段时间以来,我一直在尝试不同的方法,但我已经达到了无论我做什么都会出错的地步。

所以这就是我试图做的。首先,我创建一个随机数并将其添加到数组中:

for(.......){
  random[i] = Math.floor(Math.random() * (word.length));

然后将另一个随机数添加到数组中:

randomkey[i] = Math.floor(Math.random() * (word.length));

然后我创建这个函数:

var accept=true;
// word is a text (length:22)
function acceptRandom(random,word){
  stop:
    for(var i=0;i<randomkey.length+1; i++){
      if(word[i] != word[random])
        accept = true;
      else {
        accept = false;
        break stop;
      }
    }
    if(accept == false){
      newrandom = Math.floor(Math.random() * (word.length));
      // Random number exists so we call the function again with a new value
      acceptRandom(newrandom,word);
    } else
      return random;
}

现在,问题是当随机数已经存在时它不会返回新值。

4

2 回答 2

2

由于您正在遍历整个列表,因此总会有一个点word[i] == word[random](因为您已经将单词与自身进行了比较。)快速解决方法是:

for(var i=0;i<randomkey.length+1; i++){
    if(word[i] == word[random] && i !== random) {
        accept = false;
        break;
    }
}

您还需要返回递归调用:

if(accept == false){
      newrandom = Math.floor(Math.random() * (word.length));
      // Random number exists so we call the function again with a new value
      return acceptRandom(newrandom,word);
}

老实说,我认为您遇到了XY 问题。你到底想在这里做什么?可能有更好的方法。

于 2012-11-18T03:10:08.703 回答
0

改变:

for(.......){
  random[i] = Math.floor(Math.random() * (word.length));
// You're assigning a random number to random[i]

for(.......){
  random[i] = words[Math.floor(Math.random() * (word.length))];
// Whereas you should be assigning words[random number] to random[i]
于 2012-11-18T03:18:51.020 回答