I am trying with below code to generate 10 digits unique random number. As per my req i have to create around 5000 unique numbers(ids). This is not working as expected. It a
I don't know why noone realized that but I think the point is to generate "unique" random number which I am also trying to do that. I managed to generate 11 digits random number but I am not sure how to generate unique numbers. Also my approach is a little different. In this method I am appending number chars next to each other with for loop. Then returning long number.
public long generateID() {
Random rnd = new Random();
char [] digits = new char[11];
digits[0] = (char) (rnd.nextInt(9) + '1');
for(int i=1; i<digits.length; i++) {
digits[i] = (char) (rnd.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
Hi you can use the following method to generate 10 digit random number
private static int getRndNumber() {
Random random=new Random();
int randomNumber=0;
boolean loop=true;
while(loop) {
randomNumber=random.nextInt();
if(Integer.toString(randomNumber).length()==10 && !Integer.toString(randomNumber).startsWith("-")) {
loop=false;
}
}
return randomNumber;
}
I think the reason you're getting 8/9 digit values and negative numbers is that you're adding fraction
, a long
(signed 64-bit value) which may be larger than the positive int
range (32-bit value) to aStart
.
The value is overflowing such that randomNumber
is in the negative 32-bit range or has almost wrapped around to aStart
(since int
is a signed 32-bit value, fraction
would only need to be slightly less than (2^32 - aStart
) for you to see 8 or 9 digit values).
You need to use long
for all the values.
private static void createRandomInteger(int aStart, long aEnd, Random aRandom){
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = aEnd - (long)aStart + 1;
logger.info("range>>>>>>>>>>>"+range);
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
logger.info("fraction>>>>>>>>>>>>>>>>>>>>"+fraction);
long randomNumber = fraction + (long)aStart;
logger.info("Generated : " + randomNumber);
}