Reputation: 261
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?
Upvotes: 1
Views: 72
Reputation: 1903
The following should put you on the right track. The idea is that for the second extraction we reduce the range by one. If the number extracted is less than the previous extracted, that's good. If not, then we add 1 to it to obtain a number in range [v1+1, n]:
Random r = new Random();
int v1 = r.nextInt(n);
int v2 = r.nextInt(n-1);
if (v2 >= v1)
v2++
Upvotes: 1
Reputation: 1490
Create an array and just check if new random number is already exist in your array. While you have only loop of 4 steps it will not influence performance, but in this solution all numbers will be random.
int arr[] = new int[4];
for(int allrbA=0; allrbA<4; allrbA++) {
int num;
do{
num = randoms1.nextInt(10);
}
while(!Arrays.asList(arr).contains(num));
arr[allrbA] = num;
}
Upvotes: 0
Reputation: 61955
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.
Upvotes: 0