Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating 10 digits unique random number in java

Tags:

java

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 also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 8 or 9 numbers not 10.

public static synchronized  List generateRandomPin(){

    int START =1000000000;
    //int END = Integer.parseInt("9999999999");
    //long END = Integer.parseInt("9999999999");
    long END = 9999999999L;

    Random random = new Random();

    for (int idx = 1; idx <= 3000; ++idx){
        createRandomInteger(START, END, random);
    }

    return null;
}


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 = (long)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);
    int randomNumber =  (int)(fraction + aStart);    
    logger.info("Generated : " + randomNumber);

  }
like image 465
RajaShanmugam Avatar asked Mar 16 '11 16:03

RajaShanmugam


People also ask

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

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


1 Answers

So you want a fixed length random number of 10 digits? This can be done easier:

long number = (long) Math.floor(Math.random() * 9_000_000_000L) + 1_000_000_000L;

Note that 10-digit numbers over Integer.MAX_VALUE doesn't fit in an int, hence the long.

like image 101
BalusC Avatar answered Sep 29 '22 11:09

BalusC