Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Thursday, October 25, 2007

Random Strings

Today I created what is possibly the most efficient way to create a random string:
function randomString(length){
    var max = "";
    for (i=0;i<length; i++){
        max += "z";
    }
    return Math.round(Math.random() * parseInt(max, 36)).toString(36).toUpperCase();
}

So how, you ask, does it work? Well, it uses the fact that you can encode a number with any radix up to 36 which uses 0-9a-z. Perfect for creating a random string. SWe take the number of characters that we want and create our maximum encoded value (by repeating Z as often as necessary), and convert that into an integer. We then take that integer and use it as the upper bounds for a random number generator. We then convert that random number to a string using a radix of 36 and convert it to upper case for fun.

I'm not really thrilled about looping to create my max string but what can you do?

It would be possible to create strings without numbers by using a radix of 26 and mapping numbers to letters after the fact, but that's a lot of extra work.