如何生成两个随机数开出4? [英] How to generate two random numbers out of 4?
问题描述
我需要两个随机数选自1,2,3和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.
所以,像 rnd1 = 1;
和 RND2 = 3;
。
我试图生成它们的经典风格: INT RND =新的随机()nextInt(3)+ 1;
。而对于另外一个同样的方式,但如何保证它们不匹配?那怎么办?
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?
推荐答案
而不是实施随机性和唯一性你自己,你可以简单地填充列表的允许号码,<一个href=\"http://developer.android.com/reference/java/util/Collections.html#shuffle%28java.util.List%3C?%3E%29\">shuffle它,并采取前两个项目:
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);
这篇关于如何生成两个随机数开出4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!