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
Random random = new Random(); int rand15Digt = random. nextInt(15);
long number = (long) Math. floor(Math. random() * 9_000_000_000L) + 1_000_000_000L; Show activity on this post.
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));
}
(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With