RajaShanmugam
RajaShanmugam

Reputation: 185

Generating 10 digits unique random number in 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);

  }

Upvotes: 15

Views: 120829

Answers (10)

You can use SecureRandom class to generate random long number. I always use java.security.SecureRandom in any security decisions and generatin security code like OTP. It make cryptographically strong random values by using a cryptographically strong pseudo-random number generator. Using java.security.SecureRandom make ensure that generated number is unique and secure.

 public static long generate() {
    try {
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        long l = secureRandom.nextLong(System.currentTimeMillis());
        return 1000000000 + l;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

Upvotes: 0

Amol Pednekar
Amol Pednekar

Reputation: 127

A general solution to return a 'n' digit number is

Math.floor(Math.random() * (9*Math.pow(10,n-1))) + Math.pow(10,(n-1))

For n=3, This would return numbers from 100 to 999 and so on.

You can even control the end range, i.e from 100 to 5xx but setting the "9" in the above equation "5" or any other number from 1-9

Upvotes: 1

scylla
scylla

Reputation: 134

I would use

long theRandomNum = (long) (Math.random()*Math.pow(10,10));

Upvotes: 2

rawsly
rawsly

Reputation: 402

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));
}

Upvotes: 4

BalusC
BalusC

Reputation: 1109745

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.

Upvotes: 50

Robert H&#246;glund
Robert H&#246;glund

Reputation: 979

This is a utility method for generating a fixed length random number.

    public final static String createRandomNumber(long len) {
    if (len > 18)
        throw new IllegalStateException("To many digits");
    long tLen = (long) Math.pow(10, len - 1) * 9;

    long number = (long) (Math.random() * tLen) + (long) Math.pow(10, len - 1) * 1;

    String tVal = number + "";
    if (tVal.length() != len) {
        throw new IllegalStateException("The random number '" + tVal + "' is not '" + len + "' digits");
    }
    return tVal;
}

Upvotes: 0

Ganesa Vijayakumar
Ganesa Vijayakumar

Reputation: 2602

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;
}

Upvotes: -2

Reza Rachman
Reza Rachman

Reputation: 143

this is for random number starting from 1 and 2 (10 digits).

public int gen() {
    Random r = new Random(System.currentTimeMillis());
    return 1000000000 + r.nextInt(2000000000);
}

hopefully it works.

Upvotes: -2

emiljho
emiljho

Reputation: 572

Maybe you are looking for this one:

Random rand = new Random();

long drand = (long)(rand.nextDouble()*10000000000L);

You can simply put this inside a loop.

Upvotes: -1

typo.pl
typo.pl

Reputation: 8942

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);

  }

Upvotes: 9

Related Questions