Saturday, January 8, 2011

Alphanumeric Random Number

Sometime basic things becomes tricky :-) Was trying to find out ways to generate some alphanumeric random number whose size (i.e. number of digits/alphabets) will be fixed and I should be able to decide that size. So, I came up with following algo-

1. ASCII table sequentially lists digits and alphabets e.g. ASCII code of 0 to 9 are ranging from 48 to 57. So I can use this sequential ASCII coding and convert them to Java Characters. Benefit, of course I can get rid of any array of predefined characters in my code.

2. I want to add current time to this "randomness", so need to initialize the seed of Java Random object with current timestamp. So every time I execute this, I can make sure it will be something different than previous instance.

3. As I already explained, it will be alphanumeric based, so I'll exclude special characters and thus, total number of valid ASCII chars left for me is 62 ( 0-9, A-Z, a-z ).

Now, let's see how the Java code looks like. Please let me know how random is this or any better approach :-) Cheers....   


/**
       * It will generate ID- 16 digit ID
       * ASCII Table
       * 0-9 - ASCII code 48-57
       * A-Z - ASCII code 65-90
       * a-z - ASCII code 97-122
       * Total: 62
       * @return
       */
      private String generateRandomID(){

            final int ID_SIZE = 16;
            final int NUM_OF_CHARS = 62;
            StringBuffer id = new StringBuffer();
            long now = new Date().getTime();
           
            // Set the new Seed as current timestamp
            Random r = new Random(now);
           
            int index = 0;
            int x = 0;
           
            while(x < ID_SIZE){
                  index = r.nextInt(NUM_OF_CHARS);
                  System.out.println("Index="+ index);
                  if(index < 10){
                        id.append((char)(48 + index));
                  }
                  else if(10 <= index && index <36){
                        index = index - 10;
                        id.append((char)(65 + index));
                  }else{
                        index = index - 36;
                        id.append((char)(97 + index));
                  }
                  x++;
            }
           
            return id.toString();
      }