How to calculate the possibilities of duplication for random number within a range in Java


To get the duplicate numbers for random numbers in a range, loop through and create two Random class objects −

Use nextInt() to get the next number −

intrandVal1 = new Random().nextInt(50);
intrandVal2 = new Random().nextInt(50);

Now, compare both the above numbers −

if (randVal1 == randVal2) {
   System.out.println("Duplicate number = "+randVal1);
}

All the above is to be done in a loop −

for (int i = 1; i <= 50; i++) {
   intrandVal1 = new Random().nextInt(50);
   intrandVal2 = new Random().nextInt(50);
   if (randVal1 == randVal2) {
      System.out.println("Duplicate number = "+randVal1);
   }
}

Example

import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      for (int i = 1; i<= 50; i++) {
         int randVal1 = new Random().nextInt(50);
         int randVal2 = new Random().nextInt(50);
         if (randVal1 == randVal2) {
            System.out.println("Duplicate number = "+randVal1);
         }
      }
   }
}

Output

Duplicate number = 35
Duplicate number = 28

Updated on: 30-Jul-2019

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements