6

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?

Amin
  • 1,643
  • 16
  • 25
  • Is this a math question? – shmosel Oct 26 '18 at 05:10
  • ten to the power of `n-1` will give the lower limit, to the power of `n` the upper (plus/minus one) - e.g. `Math.pow(10, n)` – user85421 Oct 26 '18 at 05:12
  • For really large numbers, say more than 10 digits, you can generate one digit after the other and concatenate them. Not the fastest approach, but it would work. – Henry Oct 26 '18 at 05:13
  • Your image is not in sync with the question you wrote in your post. "Suppose I take parameter (int length) and return String" It asks to take input as two integers and return a random number between min and max. I have posted my answer as per your screenshot as that is the actual given question to you. – Pushpesh Kumar Rajwanshi Oct 26 '18 at 05:36

7 Answers7

4

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.

Amin
  • 1,643
  • 16
  • 25
  • If you read the screenshot (which is the actual problem to be solved and I know OP has quoted it differently which is not right), it says the method will take two integer as input, min and max and the method should return a random number between them. Since the number is between two integers only, it will remain within integer limits. So don't think we need to solve the problem for indefinitely large numbers. Although initially I also did similar solution but don't think this is what OP really needs that seeing the screenshot in post. – Pushpesh Kumar Rajwanshi Oct 26 '18 at 07:27
  • 1
    as mentioned by him, he want to solve second problem not first problem and second problem accept one length argument and return random number with that length. – Amin Oct 26 '18 at 10:10
  • WITH THIS LINE SHOWN THIS ERROR := static List NUMBERS_WITHOUT_ZERO = List.of('1', '2', '3', '4', '5', '6', '7', '8', '9'); static List NUMBERS_WITH_ZERO = List.of('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); "References to interface static methods are allowed only at source level 1.8 or " i am using MAC OS – Nikhil Boriwale Oct 26 '18 at 13:47
  • Thanks @Amin Problem solve : i am adding one Code in pom.xml = 1.8 1.8 – Nikhil Boriwale Oct 26 '18 at 14:18
  • 1
    Your welcome. you can use `Arrays.asList` instead of `List.of` and then you don't need java 1.8 anymore. – Amin Oct 26 '18 at 15:01
3

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);
    }
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • if suppose i give input 2 then i want 10 to 99 or if i put 4 then 1000 to 9000 .Then how can i do this? – Nikhil Boriwale Oct 26 '18 at 05:25
  • For 4, you surely want 1000 to 9999 instead of 9000? What is not working for you? Just put whatever length you want, as long as the resulting numbers are in integer range. – Robby Cornelissen Oct 26 '18 at 06:31
1

I think this should work:

int n = min + (int) (Math.random() * (max - min + 1));
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • This is incorrect. If I pass min as 1 and max as 10 then 10-1+1 = 10 which means rand*10 may return 9 and you adding min + 9 = 10 and 10 should be exclusive. You shouldn't add +1 in (max - min + 1) – Pushpesh Kumar Rajwanshi Oct 26 '18 at 05:34
  • @PushpeshKumarRajwanshi where did you see that max would be 10? Just use 9 and it works perfectly. – Henry Oct 26 '18 at 05:44
  • @Henry: For min =1 and max = 10 (int) (Math.random() * (max - min + 1)) = (int) (Math.random() * (10 - 1+ 1)) = (int) (Math.random() * (10)) which can never be 10 but can be 9. And since we are are adding min into it (min + (int) (Math.random() * (max - min + 1))) = 1 + 9 = 10 Which should be excluded. Why is why I said, we don't need to add 1 while doing max - min – Pushpesh Kumar Rajwanshi Oct 26 '18 at 07:07
  • @PushpeshKumarRajwanshi I fully understand that. The point is, you are making an assumption here that is nowhere stated. If we take `max` to mean the highest value that can actually be achieved all is fine. One example would be the range given by OP min=100, max=999. – Henry Oct 26 '18 at 07:11
  • @Henry: Well, it is stated. If you see the screenshot in post, it says "If we pass the input as 400 and 4000 then this method should return any number between 400 and 4000". Notice it says any number "between" and between means excluding the given min max numbers :) But if you assume that both given values are inclusive then its fine but we should specifically mention any assumptions, like including min and max? Nothing like a big thing indeed. That was just my little suggestion although the concept of the answer is right. – Pushpesh Kumar Rajwanshi Oct 26 '18 at 07:35
1
public void generateRandomNumber(int length){
     int max= Math.pow(10,length)-1;
     int min=Math.pow(10,length-1);
     int range = max - min + 1;
     int randomNumber = (int) (Math.random() * range) + min;
}     

Math.random() returns a value between greater than equal to 0.0 but less than 1.0

Gautham M
  • 4,816
  • 3
  • 15
  • 37
  • 1
    previous answer was posted before the question was edited. Now i have edited the answer according to the question – Gautham M Oct 26 '18 at 05:31
1

You need this method,

public static int getRandNum(int min, int max) {
    return (int)(Math.random()*(max-min)) + min;
}

Like you asked in your post in image, this method returns a random number between min (inclusive) and max (exclusive).

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
0

My variant

 public class RandomGen {

    public int getRandom(int min, int max) {
    Random random = new Random();
    return random.nextInt((max - min) + 1) + min;
     }
   }

    public class App {
      public static void main(String[] args) {
      RandomGen value = new RandomGen();
      System.out.println(value.getRandom(300, 400));
     }
    }
Dyakin Anton
  • 20
  • 2
  • 4
0

Not sure if this is still relevant if I understood, the solution comes out of the box in java.

Random sr = new SecureRandom();
IntStream ints = sr.ints(3, 100, 999);
Iterator<Integer> it = ints.boxed().collect(Collectors.toSet()).iterator();

The iterator is just like any other so you can play with it at will. Let me know if this is not what you want.

Yaffah
  • 31
  • 1