How to generate three unequal numbers?

Серёга Боров :

Here the number generation :

for( int i=0; i<3; i++) {
    int randomNumbers = random.nextInt(10) + 1; 
}

And here I can receive the same digits.

For example: 5,7,5;

But I need to receive only different numbers: 5,1,9.

Is it possible maybe with some little piece of code or I should write some method for it?

Andronicus :

You can use a Set which holds only unique values:

Set<Integer> randomInts = new HashSet();
while(randomInts.size() < 3) {
    randomInts.add(random.nextInt(10) + 1);
}

Of course, you need to face oversampling, but this approach scales very easily if performance isn't the most important.

Guess you like

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