12 Digit unique random number generation in Java
Improved checked solution using StringBuilder():
public static long generateRandom() {
Random random = new Random();
StringBuilder sb = new StringBuilder();
// first not 0 digit
sb.append(random.nextInt(9) + 1);
// rest of 11 digits
for (int i = 0; i < 11; i++) {
sb.append(random.nextInt(10));
}
return Long.valueOf(sb.toString()).longValue();
}
(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
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));
}