random function
#3

Quote:
Originally Posted by LarzI
Посмотреть сообщение
Well I'm not sure how efficient it is, but anyway:
pawn Код:
RandomString()
{
    #define RESULT_SIZE (6) // change (6) to how many letters you want + 1 (5 letters = 6, 4 letters = 5)
   
    new
        szAlphabet[] = "abcdefghijklmnopqrstuvwxyz",
        szResult[ RESULT_SIZE ],
        iRand,
        i
    ;
       
    do
    {  
        if( i == ( RESULT_SIZE - 1 ) )
        {
            szResult[ i ] = '\0';
            break;
        }
           
        iRand = random( strlen( szAlphabet ) );
        szResult[ i++ ] = szAlphabet[ iRand ];
       
        strdel( szAlphabet, iRand, ( iRand + 1 ) );
           
    } while( strlen( szResult ) < ( RESULT_SIZE ) );
   
    return szResult;
}
Edit: Updated the code a bit.

This code will create a random number from 0 to the length of szAlphabet (which decreases for every loop), then it will format the string szResult with whatever letter is at the position the random number is (for example if the random number is 5, then the character positioned at cell 5 (character #6) in szAlphabet will be added to szResult).

After that, it will delete the already added character from the szAlphabet string, making it impossible for that character to being picked again.

This whole thing will loop until szResult has reached its maximum length.
Thanks a lot, works very well
Reply


Messages In This Thread
random function - by maverape - 20.01.2013, 23:04
Re: random function - by LarzI - 20.01.2013, 23:39
Re: random function - by maverape - 21.01.2013, 00:06

Forum Jump:


Users browsing this thread: 1 Guest(s)