vendredi 3 mai 2019

Don't Generate Same Random Number in C +- 2

srand(time(NULL));

for(i = 0; i < 100; i++)
{
   int randomNumber = (rand() % 100) + 1  // gets a random number from 0 - 100.
   // do stuff
}

I've currently got a random number variable which stores a number from 0-100 in each iteration of the for loop, and the code below then does stuff with that random number variable. However I've noticed that with each iteration of the loop, sometimes the same random number gets generated, and other times it generates a number very close to the one I've already generated. E.g: when
i = 1 the randomNumber might be 50, but when i = 2, it could be 51. This is super annoying for the thing I'm coding. Is there a way I can make it so that if it generates 50 the first time, the second time it has to generate a number 2 integers away from the one it just generated. E.g. if it just generates 50, then the second time it can't generate 48,49,50,51,52, but it still generates between 0-100, just skipping these numbers. Then it repeats the same thing when a new randomNumber is generated.




Aucun commentaire:

Enregistrer un commentaire