[英]generating pairs of random numbers in java such that p !=q
I am trying to create pairs of random integers in the range [0,n)
. 我试图在
[0,n)
范围内创建成对的随机整数。 I need to make sure that for any input n
, the numbers created ,say p,q are such that p != q
我需要确保对于任何输入
n
,创建的数字,比如p,q,使得p != q
I tried to use java.util.Random
with seed
sothat I can reproduce the result ..I tried inputs 100,200,400,800
and they all created p,q such that p !=q
.But at 1600 two pairs were with p == q
我尝试使用
java.util.Random
和seed
sothat我可以重现结果..我尝试输入100,200,400,800
并且他们都创建了p,q使得p !=q
。但是在1600两对与p == q
public static void generate(int size){
Random ran = new Random();
ran.setSeed(123456L);
for(int i =0;i<size;i++){
int p = ran.nextInt(size);
int q = ran.nextInt(size);
if(p==q)
System.out.println(p+" equals "+q);
//else
//System.out.println(p+" "+q);
}
}
public static void main(String[] args) {
generate(1600);
}
this gave 这给了
692 equals 692
843 equals 843
I am sure there is some way to make sure that p != q for any input n.. but I cannot recall the math needed 我确信有一些方法可以确保p!= q对于任何输入n ..但我不记得所需的数学
Can someone help? 有人可以帮忙吗?
Just keep picking until they don't match. 只要继续挑选,直到它们不匹配。
int p = ran.nextInt(size);
int q;
do {
q = ran.nextInt(size);
} while(p==q);
Generate one number in [0,n) and the other one in [0,n-1) If the second one is superior (inclusive) to the first one, add one. 在[0,n)中生成一个数字,在[0,n-1]中生成另一个数字如果第二个数字优于(包括)第一个,则添加一个。
int p = ran.nextInt(size);
int q = ran.nextInt(size-1);
if (q>=p){
q++;
}
Add 1 to n
in a List
. 在
List
添加1 to n
。 Then use Collection.Shuffle to shuffle the whole list
. 然后使用Collection.Shuffle来整理整个
list
。 It will shuffle the list with equal likelihood. 它会以相同的可能性洗牌。 Then get any 2 from the list
然后从列表中获取任何2
For example 例如
ArrayList a = new ArrayList();
for(int i = 1;i <= n; i++)
a.add(i);
Collections.shuffle(a);
int first = (int)a.get(0);
int second = (int)a.get(1);
One of the solutions is: 其中一个解决方案是:
In almost 100% step 2 will be executed no more than a couple of times. 几乎100%的步骤2将执行不超过两次。
But ensure than n is more than 1 because you will have an endless loop in another case (but anyway, you can't get correct results with any algorithm) 但是确保n大于1,因为在另一种情况下你会有无限循环(但无论如何,你不能用任何算法得到正确的结果)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.