20.01.2013, 23:39
Well I'm not sure how efficient it is, but anyway:
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.
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;
}
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.