I'm making script and it generates random numbers in milliseconds (Range 20-100), let's say it generated delays: 30, 40, 42 (All < (less than) 50)
Now I want to make it so 4th delay cant be again less than 50, I tried this:
I tried using for loop, but my when i use this code script doesn't work at all anymore / it won't toggle or anything.
Just imagine you made script and it generates random numbers from 20-100 and you dont want 4 in row delays that are less than 50, what would you do? Thanks.
for (int i = 0; i < 4;)
{
// Total Delay aka delay1+delay2
if (totaldelay < 50)
{
i++;
}
// Should make totaldelay > 50
if (i == 3)
{
delay1 = RandomInt(75, 105);
}
// Reset to 0 so it checks from 0 again
if (total > 50)
{
i = 0;
}
}
If I understand the question correctly, you don't want four consecutive numbers to be all less than 50. You can achieve this by simply keeping a count and adjusting your behaviour so that you generate a different number if the previous three were all less than 50.
If you're looking for a standalone C++ function to do that (give you one random number per call, with your specific added limitations), you can use something like:
int getMyRand() {
// Keep track of how many consecutive under-50s already done.
// Careful in multi-threaded code, may need thread-local instead.
static int consecUnder50 = 0;
int number;
// If last three were all < 50, force next one to be >= 50.
if (consecUnder50 == 3) {
number = rand() % 51 + 50; // 50-100 (inclusive).
} else {
number = rand() % 81 + 20; // 20-100 (inclusive).
}
// If less, record it, otherwise restart count.
if (number < 50) {
++consecUnder50;
} else {
consecUnder50 = 0;
}
// Give caller the number.
return number;
}
Don't forget to seed the random number generator before using this, and be aware that C++ has better random number generators, although rand()
is usually fine unless you're a statistician or cryptographer:-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.