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.


  1. Isn't it easier to use

    var max = new Array(length).join("z")

    Instead of the for-loop?

  2. Hmm. I'm not entirely sure that its easier to understand. It's certainly fewer characters. You would also want to run a test to see if joining an array is faster than iterating through a loop.

    Also, the correct code ie would be:

    var max = new Array(length+1).join("z")

    Of course, an ever better solution is:

    var max = Math.pow(36,length) - 1;