1

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
  • 25,419
  • 17
  • 47
  • 88

3 Answers3

5

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.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
5

Here's a way that avoids rejection sampling: generate one number up to 10, one up to 9, and up to 8. Avoid repeats by incrementing. This guarantees a uniform distribution.

int a = random.nextInt(10) + 1;
int b = random.nextInt(9) + 1;
if(b >= a) { b++; }
int c = random.nextInt(8) + 1;
if(c >= (a > b ? b : a)) { c++; }
if(c >= (a > b ? a : b)) { c++; }
kaya3
  • 47,440
  • 4
  • 68
  • 97
2

In my point of view, using a while loop is possible to generate random numbers with different digits. Use while loop to check whether the number was generated earlier and if it was then generate new number.