简体   繁体   English

如何从4中生成两个随机数?

[英]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. 我需要1个,2个,3个和4个中的两个随机数,但是它们不能相同,我需要两个不同的变量。

So, something like rnd1 = 1; 因此,类似于rnd1 = 1; and rnd2 = 3; 并且rnd2 = 3; .

I tried to generate them classic style: int rnd = new Random().nextInt(3) + 1; 我试图生成它们的经典样式: 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. 将第一个值分配给第二个值,然后使用while循环,直到两个值不相等。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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