简体   繁体   中英

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) . I need to make sure that for any input n , the numbers created ,say p,q are such that 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

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

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.

int p = ran.nextInt(size);
int q = ran.nextInt(size-1);

if (q>=p){
    q++;
}

Add 1 to n in a List . Then use Collection.Shuffle to shuffle the whole list . It will shuffle the list with equal likelihood. Then get any 2 from the list

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:

  1. Generate first number
  2. Generate second number
  3. While second number equals to first number return to step 2

In almost 100% step 2 will be executed no more than a couple of times.

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)

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