PDA

View Full Version : How to create randoms with exceptions

coool
17/12/2016, 01:44 PM
I have created a Random function But It sometimes or frequently outputs the same result because I have just 4 things to get a random of.
Is there any way to create a random with exception For ex:I create a random function but how to make exceptions like my random result is 2nd variable and how to prevent it from being the same....

Simply, there are 4 numbers to get random of.... The random results 1. so how to prevent from being one again in result.

Dayrion
17/12/2016, 01:54 PM
I did that but I think you can optimize it.
main()
{
printf("%i", randomEx(5, _, 0, 1, 2, 4, 5)); // print 3
}

randomEx(max, min = 0, ...)
{
new
maxarg = numargs(),
nb = random(max - min) + min;

while(maxarg != 0)
{
if(nb == getarg(maxarg))
{
maxarg = numargs();
nb = random(max - min) + min;
}
else
maxarg--;
}

return nb;
}

NaS
17/12/2016, 04:47 PM
randomex(max, exception = -1)
{
if(exception == -1) return random(max);

new r = random(max - 1);

return (r == exception ? r + 1 : r);
}

Way simpler than the one above. But only works for preventing the same value 2 times. This can still happen: 2, 3, 2, 3, 2, 3 etc.

If your first result was 2 (out of 0-3), it will get a random value of 0-2. If the value is your last value, it will add one, else take that value. If the first value was the maximum value, it cannot be chosen again (hence "max - 1").

coool
17/12/2016, 04:58 PM
OK, But will this work or not??

new rand = Random(5); //1st random result.
new rand2 = Random(5); //2nd random result.
while (rand2 == rand) {
rand2 = Random(5); //continue randoming it until 1st and 2nd results are not same.
}

SickAttack
17/12/2016, 05:07 PM
Use an array, something like:
new array = {0, 1, 2, 3, 4}, count = sizeof(array), selected;
selected = random(count);
array[selected] = array[-- count];
selected = random(count);
array[selected] = array[-- count];

and so on...

Note that this example is only for consecutive numbers, you'd have to write your own version if you'd like to use any value.

NaS
17/12/2016, 05:56 PM
OK, But will this work or not??

That would work totally fine, just theoretically not as efficient (it can in very rare circumstance produce long loops, since the random inside while could return the same value over and over again (just theoretically!)).