How to create randoms with exceptions
#1

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.
Reply
#2

I did that but I think you can optimize it.
PHP код:
main()
{
    
printf("%i"randomEx(5_01245)); // print 3
}

randomEx(maxmin 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;

Reply
#3

PHP код:
randomex(maxexception = -1)
{
if(
exception == -1) return random(max);
new 
random(max 1);
return (
== exception 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").
Reply
#4

OK, But will this work or not??
Quote:

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.
}

Reply
#5

Use an array, something like:
pawn Код:
new array = {0, 1, 2, 3, 4}, count = sizeof(array), selected[5];
selected[0] = random(count);
array[selected[0]] = array[-- count];
selected[1] = random(count);
array[selected[1]] = 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.
Reply
#6

Quote:
Originally Posted by coool
Посмотреть сообщение
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!)).
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)