Kilise
Kilise

Reputation: 1089

Add to array, check if id exists and randomly change it

I've been trying different ways for a while and I've reached that point where whatever I do just gets wrong.

So this is what I've tried to do. First I create a random number and add it to an array:

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

Then another random number is added to the array:

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

Then I create this function:

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;
}

Now, the problem is that it won't return the new value when the random number already exists.

Upvotes: 0

Views: 266

Answers (2)

SomeKittens
SomeKittens

Reputation: 39522

Since you're iterating through the whole list, there will always be a point where word[i] == word[random] (because you've comparing the word to itself.) A quick fix would be:

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

You'll also need to return your recursive call:

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);
}

Honestly, I think you've run into the XY problem. What exactly are you trying to do here? There's probably a better way.

Upvotes: 2

dda
dda

Reputation: 6213

Change:

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

to

for(.......){
  random[i] = words[Math.floor(Math.random() * (word.length))];
// Whereas you should be assigning words[random number] to random[i]

Upvotes: 0

Related Questions