I want to create a random number generator that can not return the last value it generated.
So far I have created a simple generator using
Random.Range(0, 4)
,
however this could return a value two times in a row, which is unwanted for my project.
How can I improve on this code?
CodePudding user response:
What you should do is create an integer representing the last random number returned by the number generator. Then you can run the generator in a while loop such that it never returns the same number it returned in the previous run.
int lastRandomNumber = -1;
int GiveRandomNumber()
{
int randomNumber = lastRandomNumber;
while(randomNumber==lastRandomNumber)
randomNumber = Random.Range(0, 4);
lastRandomNumber = randomNumber;
return randomNumber;
}
CodePudding user response:
To code something more elegant and avoid an unwanted loop, you'll need to make an array where you'll remove the last number. If you want to simply remove one number which is the last random one, you can either reset (if the list is small enough like 0-4) or re-add the number in your list if it's very big.
In other words, if you want to re-create a list each time, it should look something like this:
var rand = new Random();
int[] randoms = new int[5];
int lastRandom = 2; // For exemple/start
int iter = 0;
for (int i = 0; i < randoms.Length; i )
{
if (iter == lastRandom) iter ;
randoms[i] = iter ;
}
int newRandom = randoms[rand.Next(randoms.Length)];
Console.WriteLine(newRandom);
It may look overkill, but it's the most flexible and best way to do it. As like you said, if we simply re-roll the random, it can roll on it over and over which can make some lag (on large scale).