Generating 10 digits unique random number in java

前端 未结 9 596
执念已碎
执念已碎 2020-12-09 10:52

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

相关标签:
9条回答
  • 2020-12-09 11:18

    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.

    0 讨论(0)
  • 2020-12-09 11:20

    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

    0 讨论(0)
  • 2020-12-09 11:28

    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.

    0 讨论(0)
  • 2020-12-09 11:28

    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;
    }
    
    0 讨论(0)
  • 2020-12-09 11:35

    I would use

    long theRandomNum = (long) (Math.random()*Math.pow(10,10));
    
    0 讨论(0)
  • 2020-12-09 11:40

    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.

    0 讨论(0)
提交回复
热议问题