Generating random characters?
#1

Hi.. I want to generate some random letters and then put them into textdraw.

For example, it want it to generate:


X 4 K 8 S K O W M S N P Q

And then I put it into a textdraw string.. how do this?
Reply
#2

pawn Код:
GenerateRandomLetters(len) {
    new Letters = ['A','B','C','D','E','F','G','H','I','J','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    new Ret[len];
    for(new i = 0; i < len; i++) {
        format(Ret, sizeof(Ret), "%s %s", Ret, Letters[i]);
    }
    return Ret;
}
Something like this - untested - I'm a PHP developer, may be a little wrong.
Reply
#3

Quote:
Originally Posted by Isolated
Посмотреть сообщение
pawn Код:
GenerateRandomLetters(len) {
    new Letters = ['A','B','C','D','E','F','G','H','I','J','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    new Ret[len];
    for(new i = 0; i < len; i++) {
        format(Ret, sizeof(Ret), "%s %s", Ret, Letters[i]);
    }
    return Ret;
}
Something like this - untested - I'm a PHP developer, may be a little wrong.
You can not create arrays with non-fixed (non-constant) size - it must be known for compiler while it's compiling the code.
Also, using arrays is quite slow, this one is better (I just wrote it and tested - working):
pawn Код:
// Generate random character (a-z A-Z only)
stock randomchar()
    return ( random(1000) %2 ==0 ) ? (65 + random(26)) : (97 + random(26));
Example usage:
pawn Код:
main() {
    new RandomString[16];
    for(new i = 0; i < sizeof(RandomString); i++)
        format( RandomString, sizeof( RandomString ), "%s%c", RandomString, randomchar());
    printf("%s", RandomString);
}

//Possible output: AswHqLkMEJxCNte
Edit.

A little modification to the generator, so that it can also generate digits (if you want so)
pawn Код:
stock randomchar( bool:useDigits = false ) {
    if( useDigits ) {
        if( random(1000)%2==0 )
            return 48 + random(10);
        else
            return (random(1000)%2==0) ? (65 + random(26)) : (97 + random(26));
    } else
        return ( random(1000) %2 ==0 ) ? (65 + random(26)) : (97 + random(26));
}
Greetings.
Reply
#4

Thanks a lot. Sent you another PM aswell.
Reply
#5

Quote:
Originally Posted by LetsOWN[PL]
Посмотреть сообщение
A little modification to the generator, so that it can also generate digits (if you want so)
pawn Код:
stock randomchar( bool:useDigits = false ) {
    if( useDigits ) {
        if( random(1000)%2==0 )
            return 48 + random(10);
        else
            return (random(1000)%2==0) ? (65 + random(26)) : (97 + random(26));
    } else
        return ( random(1000) %2 ==0 ) ? (65 + random(26)) : (97 + random(26));
}
Greetings.
A little nitpicking here, but mod is inherently very slow. If you want to check if a number is odd, you may use:
pawn Код:
isOdd(number) return number & 1;
Also using 'A' and 'a' instead of 65 and 97 may make the intentions a bit more clear.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)