lundi 22 juin 2015

Using rand() to get a number but that number can't be the number that was last generated

I want to use std::rand() to generate a number between 0 and amountOfNumbers, but the generated number can't be the same number that was last generated.

I wrote this function:

void reroll() {
  int newRand;

  while (true) {
    newRand = std::rand() % (amountOfNumbers);
    if (newRand == lastNumber) {
      continue;
    }
    lastNumber = newRand;
    break;
  }

  // do something with newRand
  // ...
}

amountOfNumbers is just an int (> 1) that defines the upper bound (e.g. 5 so the possible number range is 0 to 4). lastNumber which is initially -1 stores the last generated number.

I was wondering if there's a better way to write this.

The function seems to be working so far, but I'm not sure if my code is flawless... it looks kind of bad. That while (true) makes me feel a bit uneasy.




Aucun commentaire:

Enregistrer un commentaire