Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating pairs of random numbers in java such that p !=q

Tags:

java

random

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?

like image 701
damon Avatar asked Dec 15 '22 09:12

damon


1 Answers

Just keep picking until they don't match.

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

do {
    q = ran.nextInt(size);
} while(p==q);
like image 171
James Montagne Avatar answered Jan 14 '23 18:01

James Montagne