H3ll0 - 15 days ago 6

Android Question

I have two randomly generated variables. LoadG4 is outputted to one button and the other 3 buttons have a differing value for randoms1 generated. My aim here is to ensure that no value of the randomly generated randoms1 is equal to LoadG4. For example if the range is between 0 to 9 and LoadG4 ends up being 3, the other random numbers from randoms1.nextint... must not be 3. They could be 7, 4, or 5 for example, but not the same as LoadG4.

Here's my code:

`Random GenerateG4 = new Random();`

int loadG4 = GenerateG4.nextInt(10);

Random randoms1 = new Random();

final TextView number = (TextView) findViewById(R.id.number);

number.setText(""+loadG4);

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

selectrb[allrbA].setText(""+randoms1.nextInt(10));

}

selectrb[rbselector].setText(""+loadG4);

How could I do this?

Many thanks in advance.

UPDATED CODE:

`if (rbvalue==loadG4) {`

int realrbvalue = rbvalue++;

selectrb[allrbA].setText(""+realrbvalue);

}

else {

selectrb[allrbA].setText(""+rbvalue);

}

}

Why does this still not work?

Answer

A variation of the comment:

```
for(int allrbA=0; allrbA<4; allrbA++) {
int r = randoms1.nextInt(10 - 1); // range one less because one will be skipped
if (r == load4G) r = 9; // don't want this one, take the one
// that would have been included in the full range
selectrb[allrbA].setText("" + r);
}
```

The comment proposal is to add one to `r`

for any random value where `r >= load4G`

- this implies that the final value of `r`

could never equal load4G - which has the same net effect.

With a loop to re-generate a new random:

```
for(int allrbA=0; allrbA<4; allrbA++) {
int r;
do {
r = randoms1.nextInt(10); // get a random number
} while (r == load4G); // until it is different
selectrb[allrbA].setText("" + r);
}
```

If *all* the random numbers must be different a (Fisher-Yates) shuffle would be an appropriate solution.

Source (Stackoverflow)

Comments