Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

12 Digit unique random number generation in Java

Tags:

java

i was working on an application where we need to generate some unique number and practically there was no predefined restrictions so was using java UUD generator and was working fine. Now we are given a new requirements to generate 12 digits unique random number.

Can any one point me some good way/algorithm to achieve this as i can not see any possibility in the UUID generated number.

Thanks in advance

like image 578
Umesh Awasthi Avatar asked Jan 11 '11 09:01

Umesh Awasthi


People also ask

How do you generate a 15 digit unique random number in Java?

Random random = new Random(); int rand15Digt = random. nextInt(15);

How do you generate a random 10 digit number in Java?

long number = (long) Math. floor(Math. random() * 9_000_000_000L) + 1_000_000_000L; Show activity on this post.


2 Answers

Generate each digit by calling random.nextInt. For uniqueness, you can keep track of the random numbers you have used so far by keeping them in a set and checking if the set contains the number you generate each time.

public static long generateRandom(int length) {
    Random random = new Random();
    char[] digits = new char[length];
    digits[0] = (char) (random.nextInt(9) + '1');
    for (int i = 1; i < length; i++) {
        digits[i] = (char) (random.nextInt(10) + '0');
    }
    return Long.parseLong(new String(digits));
}
like image 121
dogbane Avatar answered Sep 22 '22 22:09

dogbane


(long)Math.random()*1000000000000L

But there are chances of collision

Why not use sequence? Starting from 100,000,000,000 to 999,999,999,999? keep a record of last generated number.


Edit: thanks to bence olah, I fixed a creepy mistake

like image 42
Nishant Avatar answered Sep 21 '22 22:09

Nishant