Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate a unique random number each time when I run my application? [closed]

In my application, i want to generate 9 digit random numbers such that they r unique. Only one 9 digit random number should be generated each time i run the application and it should be unique. Later i want to save this number along with its associated data in a .txt file so that i can retrive the data associated with this unique number when required. How should i achieve this?

like image 818
bhabs Avatar asked Apr 06 '11 10:04

bhabs


People also ask

How do you generate unique random numbers every time?

You could combine the Random Class & system time (or a function using system time) e.g. Random random = new Random(System. nanoTime()); int randomInt = random. nextInt(1000000000);

Can you generate the same random numbers everytime?

No, they're called pseudorandom because they're not truly random in the mathematical sense, only an approximation. A PRNG that generates distinct numbers each time it's run is still pseudorandom.


2 Answers

Do you want them to be truly random or truly unique? You can only have one of these.

If you want them to be truly random, then just randomly pick 9 digits from 0-9 and construct them into your number. There will be a small chance of a duplication, especially over larger numbers of iterations. It will be truly random, though.

If you want them to be truly unique, then you have to store every one in a database to ensure there are no duplicates. If you generate a duplicate, you'll need to regenerate or just increment the number and try again. If this is what you're looking for, it might be good to try just incrementing the value starting at one.

like image 83
Erick Robertson Avatar answered Nov 15 '22 07:11

Erick Robertson


For unique number try: (new Date()).getTime() it will never be the same unless you are generating multiple number in a sec.

like image 23
Harry Joy Avatar answered Nov 15 '22 07:11

Harry Joy