How To Generate Two Random Numbers Out Of 4?
I need two random numbers out of 1, 2, 3 and 4, but they cannot be the same and I need them in two different variables. So, something like rnd1 = 1; and rnd2 = 3;. I tried to gen
Solution 1:
Rather than implementing the randomness and unicity yourself, you could simply populate a list with the allowed numbers, shuffle it and take the first two entries:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Collections.shuffle(list);
rnd1 = list.get(0);
rnd2 = list.get(1);
Solution 2:
Randomrandom=newRandom();
intrnd1= random.nextInt(3) + 1;
intrnd2= rnd1;
while(rnd2 == rnd1) {
rnd2 = random.nextInt(3) + 1;
}
Solution 3:
Well, the easiest way could be:
Randomrandom=newRandom();
intrnd1= random.nextInt(3) + 1;
int rnd2;
do {
rnd2 = random.nextInt(3) + 1;
} while (rnd1 == rnd2);
Solution 4:
Assign the first value to the second then use a while loop until the two values are not equal.
int rnd = newRandom().nextInt(3) + 1;
int rnd2 = rnd;
while(rnd2 == rnd){
rnd2 = newRandom().nextInt(3) + 1;
}
Solution 5:
int one, two;
Randomr=newRandom();
one = r.nextInt(3) + 1;
two = r.nextInt(3) + 1;
while (one == two){
two = r.nextInt(3) + 1;
Post a Comment for "How To Generate Two Random Numbers Out Of 4?"