简体   繁体   中英

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 generate them classic style: int rnd = new Random().nextInt(3) + 1; . And for the other one the same way, but how to ensure that they don't match? How to do that?

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);
Random random = new Random();
int rnd1 = random.nextInt(3) + 1;
int rnd2 = rnd1;
while(rnd2 == rnd1) {
    rnd2 = random.nextInt(3) + 1;
}

Well, the easiest way could be:

Random random = new Random();
int rnd1 = random.nextInt(3) + 1;
int rnd2;
do {
    rnd2 = random.nextInt(3) + 1;
} while (rnd1 == rnd2);

Assign the first value to the second then use a while loop until the two values are not equal.

int rnd = new Random().nextInt(3) + 1;
int rnd2 = rnd;

while(rnd2 == rnd){
  rnd2 = new Random().nextInt(3) + 1;
}
    int one, two;
    Random r = new Random();
    one = r.nextInt(3) + 1;
        two = r.nextInt(3) + 1;
    while (one == two){
            two = r.nextInt(3) + 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM