Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate any random number of any Length in Java

Tags:

java

How to generate any random number of any Length in Java? Like, to generate a number of width 3, it should be between 100 to 999. So how to code this?
In image below:
description
I want to solve second problem.
This is what I written for first problem:

public int getRandomNumberReturntypediff(int min,int max) {
    Random rand = new Random();

    int  n = rand.nextInt(1000) + 1;
    Integer.toString(n);

    System.out.println("get Random Number with return type STRING" + n);
    return n;
}

Suppose I take parameter length and return String. How can I do this?

like image 822
Nikhil Boriwale Avatar asked Oct 26 '18 05:10

Nikhil Boriwale


Video Answer


2 Answers

We use String for create number and the convert it to a BigInteger. I think the the best way for handle large number is to use BigInteger but if you need String just return that.

static List<Character> NUMBERS_WITHOUT_ZERO = List.of('1', '2', '3', '4', '5', '6', '7', '8', '9');
static List<Character> NUMBERS_WITH_ZERO = List.of('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
private static final SecureRandom random = new SecureRandom();

public static BigInteger randomNumber(int length) {
    StringBuilder res = new StringBuilder(length);
    res.append(NUMBERS_WITHOUT_ZERO.get(random.nextInt(NUMBERS_WITHOUT_ZERO.size())));
    for (int i = 2; i <= length; i++)
        res.append(NUMBERS_WITH_ZERO.get(random.nextInt(NUMBERS_WITH_ZERO.size())));
    return new BigInteger(res.toString());
}

I hope this is what you want.

like image 169
Amin Avatar answered Oct 24 '22 20:10

Amin


Since you already have the actual bounded random number generation logic in your question, I assume your struggling with the calculation of the bounds.

You can calculate the minimum and maximum values by using powers of 10:

  • Minimum = 10 ^ (length - 1)
  • Maximum = (10 ^ length) - 1

So, for example, for a number length of 3, this will give you a minimum of 100, and a maximum of 999.

Here's a complete example:

import java.util.Random;

public class Randoms {
    public static void main(String args[]) {
        System.out.println(generateRandom(3));
    }

    private static String generateRandom(int length) {
        int min = (int) Math.pow(10, length - 1);
        int max = (int) Math.pow(10, length); // bound is exclusive

        Random random = new Random();

        return Integer.toString(random.nextInt(max - min) + min);
    }
}
like image 32
Robby Cornelissen Avatar answered Oct 24 '22 21:10

Robby Cornelissen