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 numbers created, for example, p, q, are such that p != q

I tried using java.util.Random with seed sothat, I can reproduce the result. I tried the inputs 100,200,400,800 and they all created p, q such that p !=q But in 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); } 

it gave

 692 equals 692 843 equals 843 

I am sure there is some way to make sure p! = Q for any input n .. but I can’t remember the required math

Can anyone help?

+4
source share
4 answers

Just keep collecting until they match.

 int p = ran.nextInt(size); int q; do { q = ran.nextInt(size); } while(p==q); 
+6
source

Generate one number in [0, n) and another in [0, n-1) If the second is the first (inclusive) for the first, add it.

 int p = ran.nextInt(size); int q = ran.nextInt(size-1); if (q>=p){ q++; } 
+4
source

Add 1 to n to the List . Then use Collection.Shuffle to shuffle the entire List . He will shuffle the list with equal probability. Then get any 2 from the list

for instance

 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); 
+1
source

One solution:

  • Create first number
  • Create second number
  • While the second number is equal to the first number, go back to step 2

Almost 100% step 2 will be performed no more than a couple of times.

But make sure that n is greater than 1, because you will have an infinite loop in another case (but in any case, you cannot get the correct results with any algorithm)

+1
source

Source: https://habr.com/ru/post/1487890/


All Articles