What is optimal way to get four unique random number from 0-9?

Sagar Gautam :

I want to generate four random numbers in the range of 0 to 9. It's easy to generate four random numbers with Java Random class.

    Random random = new Random();

    int numbers[] = new int[4];

    for(int i=0;i<4;i++){

        numbers[i] = random.nextInt(10);

    }

With this, I can get an array of four numbers easily like, 9369, 4702 etc. In this case there may be possibility of a number to be repeated in four numbers and I don't want such repeat in numbers.

Here, I want to get all four digit in above array to be unique so that I can get output like 9543, 1234 etc.

For this, I have thought following way.

  1. Generate a random number and assigned as first number.
  2. Generate a random number and check with first number if different assigned as second number else generate random number again and repeat and so on.

Is there any better way than above method so that I can get four unique random numbers easily and quickly ?

Any kind of suggestion is appreciated.

Eran :

You can use Collections.shuffle:

// generate a List that contains the numbers 0 to 9
List<Integer> digits = IntStream.range(0,10).boxed().collect(Collectors.toList());
// shuffle the List
Collections.shuffle (digits);
// take the first 4 elements of the List
int numbers[] = new int[4];
for(int i=0;i<4;i++){
    numbers[i] = digits.get(i);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441240&siteId=1