Re: Random string

From: Chiap Zap (chiap-the-zap_at_kiuj-kavwqt.com)
Date: 10/30/04


Date: 30 Oct 2004 00:05:46 GMT

Joseph M. Newcomer wrote:
>
> It is fairly trivial to write, if you don't mind the fact that I'm cheating a bit on the
> rand() function...
>
> CString StrRandom(int len, const CString & characters)
> {
> CString result;
> LPTSTR p = result.GetBuffer(len);
> for(int i = 0; i < len; i++)
> {
> p[i] = characters[rand() % characters.GetLength()];
> }
> result.ReleaseBuffer(len);
> return result;
> }
>
> Note the use of GetBuffer to avoid the exponential cost of string concatenation.
>

Well, beside of that it seems to be the same as what I have
written.

> The problem is that the low-order bits of rand() are not as random as you might expect (a
> chi-squared test or other measure of randomness will not give a "quality" result), so
> there are better algorithms, but I leave this as an Exercise For The Reader (hint: google
> may be a good start)

I couldn't find bad randomness, when I checked the
rand()-function out some years ago, provided that the random
seed was set far enough away from the function itself, so as
early at the program start for example, and maybe also with
timeconsuming events like keystrokes inbetween.

Should you mean the bias resulting from a limited value of
RAND_MAX (usually =32767), so I would say, that this can be
neglected for probably all common uses of random strings.
Presuming a standard charset from which to chose random
characters (25+25+10+10=70), the bias would be maximally
1/(32768/70), that is approx. 0.21 percent.

Anyway. Your "google-Exercise" didn't help much, so if you have
a *simple* algorithm for better randomness, please feel free to
post it here. Thanks. :)

Greets

Chiap



Relevant Pages

  • Re: Convert CString to Char
    ... I need to convert these CString values to 'char' as the function I ... I just used google to ... remove the underscores from my email address (and please indicate which newsgroup and message). ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: CString conversion to a char* accessable string
    ... Google:) ... Personally I've always just use strcpy; to get my char * from the ... CString, the link should give you a some more information on what should ...
    (microsoft.public.vc.mfc)