Solved

How to generate Unique ID using Java Programming?

Posted on 2004-09-02
13
939 Views
Last Modified: 2011-09-20
Hi to anybody who can help,
I need to know how to generate a 6-digit unique ID using java programming. Take a scenario for example: An atm machine program prompt user for personal details. After validating the detail, it will issue an 6 digit unique customer ID and display it on the screen. (it has to be 6 digits)

Blessings,
Christine
0
Comment
Question by:InGodsGrace
  • 5
  • 3
  • 2
  • +1
13 Comments
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11961589
Hi InGodsGrace,

highest 6 digit number is 999999 .... choose a prime number less than 999999 .... call it k

- seed random number generator with current time
- generate a random number n
- first number to use will ne n mod 999999
- next, (first+k) mod 999999
- next (second +k ) mod 999999

or for that matter you can use sequential ids too !!! or is it that you need random sequential ids ? If the pattern or difference of k between consecutive ids is weak, then you will have to keep track of ids already generated which can be expensive in terms of memory

Sunnycoder
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11961596
an oops
> you need random sequential ids ?
random unique ids

Sunnycoder
0
 

Author Comment

by:InGodsGrace
ID: 11961634
Hi sunnycoder,
thks for the fast reply...

Yeah, it would be better if it could be randomise....

btw, any web link to recommend for information regarding seed and random ? i have totally no clue what it mean even though i have read info abt them..(am really weak in java)

Appreciate,
Christine
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11961754
Hi Christine,

I am not a Java programmer so all I can give you is links or C code

here you go
http://www.math.utah.edu/~alfeld/Random/Random.html
http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html
http://www.honeylocust.com/RngPack/
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11962030
import java.util.Random;

class RandomIDGenerator {
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public int generate() {
        while ( true  ) {
            // You specified you wanted a PRIME number.... otherwise just "return rand.nextInt( 999999 );"
            int num = rand.nextInt( 999999 );
            if( isPrime( num ) ) {
                return num;
            }
        }
    }

    // Probably a better primality test available somewhere!!!
    private boolean isPrime( int number ) {
        if( number %2 == 0  ) return false;
        for( int i = 3; i <= Math.sqrt( number ); i+=2 ) {
            if( number % i == 0 ) return false;
        }
        return true;
}
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11962057
hi,

sorry, forgot you need private attribute "rand"... code reposted below, including sample main() to generate 100 values...

import java.util.Random;

class RandomIDGenerator {
    private Random rand;
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public int generate() {
        while ( true  ) {
            // You specified you wanted a PRIME number.... otherwise just "return rand.nextInt( 999999 );"
            int num = rand.nextInt( 999999 );
            if( isPrime( num ) ) {
                return num;
            }
        }
    }

    // Probably a better primality test available somewhere!!!
    private boolean isPrime( int number ) {
        if( number %2 == 0  ) return false;
            for( int i = 3; i <= Math.sqrt( number ); i+=2 ) {
                if( number % i == 0 ) return false;
            }
        return true;
    }

    private static void main( String[] args ) {
        RandomIDGenerator gen = RandomIDGenerator();
        for( int i = 0; i != 100; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 11

Accepted Solution

by:
cjjclifford earned 125 total points
ID: 11962073
sorry, I've no idea where I got the idea you stated prime.... seeing things again!!!!
Code without prime is as follows:

import java.util.Random;
class RandomIDGenerator {
    private Random rand;
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public int generate() {
        return rand.nextInt( 999999 );
    }  

    public static void main( String[] args ) {
        RandomIDGenerator gen = new RandomIDGenerator();
        for( int i = 0; i != 100; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}
0
 

Author Comment

by:InGodsGrace
ID: 11969652
Thank you thank you for all ur advice, sunnycoder and cjjclifford ...

cjjclifford , I was wondering why do u put currentTimeMillis when you create a random object....what has time got to do with randoming the number? hmmm.....perhap u shed some light?? :D

And how do make the randomise number to be displayed as 6 digit if it is not 6 digit eg. to make 100 displayed as 000100

Bless ya,
Christine
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 11997281
Hello,

I refer to the codes send by cjjclifford.

import java.util.Random;
class MeowTest{
    private Random rand;
    public MeowTest() {
        rand = new Random( System.currentTimeMillis() );
    }

    public String generate() {
      String[] digit = new String[6];
      String result = "";

      for (int i = 0; i < 6; i++)
      {
            digit[i] = Integer.toString(rand.nextInt( 9 ));
            result += digit[i];
      }

      
        return result;
    }  

    public static void main( String[] args ) {
        MeowTest gen = new MeowTest();
        for( int i = 0; i != 10; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}

I hope that helps....
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 11997310
Dear christine,

The reason behind the use of System.currentTimeMillis is to generate the different number. If you do not use the currentTimeMillis, then the generated random number will always be the same. Since the currentTimeMillis will always changed, it means that the generated random number will also be various.

That is the reason.

I hope that helps

0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11997660
Hi Christine,

Sorry I didn't reply, somehow missed notification of the update to the topic. To use a Random number generator a "seed" value has to be given to the function that generates the sequence of numbers. Since the same function to generate the sequence will not change (since its standard library), if the same seed value is supplied the identical sequence of numbers will be generated.
I used System.currentTimeMillis() as the seed number since this will change every time the program is run.

With regards to how to have exactly 6 characters, the following code is probably a little simpler than that by suprapto45:

// Add this method to the class I posted before - this '0' left-pads a generated integer to a length of 6, while only calling
// Random.nextInt() once (i.e. to get the random code itself) - more efficient than repeatedly calling random.nextInt()...
public String generatePaddedCode() {
    String unpadded = Integer.toString( gen.generate() );
    StringBuffer padded = new StringBuffer();
    for( int i = 0; i != 6 - unpadded.length(); i++ ) {
        padded.append( '0' );
    }
    padded.append( unpadded );
    return padded;
}
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12004279
Sorry, some code errors in that (not calling toString() on the StringBuffer for one!) Also, the padding and the generate() methods should probably be combined, so the generation class would actually become:

import java.util.Random;
class RandomIDGenerator {
    private Random rand;
    public RandomIDGenerator() {
        rand = new Random( System.currentTimeMillis() );
    }
    public String generate() {
        String unpadded = Integer.toString( rand.nextInt( 999999 ) );
        StringBuffer padded = new StringBuffer();
        for( int i = 0; i != 6 - unpadded.length(); i++ ) {
            padded.append( '0' );
        }
        padded.append( unpadded );
        return padded.toString();
    }  

    public static void main( String[] args ) {
        RandomIDGenerator gen = new RandomIDGenerator();
        for( int i = 0; i != 100; i++ ) {
            System.out.println( gen.generate() );
        }  
    }  
}
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
method argument as final 1 62
Python - ImportError: No module named 'urllib2' 2 104
changeXy challenge 13 58
wordmultiple challenge 12 90
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
This video teaches viewers about errors in exception handling.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now