How do I generate a random string of up to a certain length?

Posted by slavy13 on Stack Overflow See other posts from Stack Overflow or by slavy13
Published on 2010-06-18T01:37:32Z Indexed on 2010/06/18 1:43 UTC
Read the original article Hit count: 222

I would like to generate a random string (or a series of random strings, repetitions allowed) of length between 1 and n characters from some (finite) alphabet. Each string should be equally likely (in other words, the strings should be uniformly distributed).

The uniformity requirement means that an algorithm like this doesn't work:

alphabet = "abcdefghijklmnopqrstuvwxyz"
len = rand(1, n)
s = ""
for(i = 0; i < len; ++i)
    s = s + alphabet[rand(0, 25)]

(pseudo code, rand(a, b) returns a integer between a and b, inclusively, each integer equally likely)

It doesn't work because shorter lengths are as likely as longer ones, meaning it's more likely to generate a shorter string than a longer one, so the result is not uniform.

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about language-agnostic