java - Generate k distinct numbers less than n -


This is the task: Generate less positive positive numbers than n without duplication.

My method is

To create an array size of the first Kashmir, we should write these numbers:

  int [] = new int [K]; // Now I am going to create another array, where I know that if (the number given in the number is // condition 1 then make the number again, continue the cycle by inserting the second number into the // array.  

I have inserted a piece of code and explanation.

  int a [] = new int [k]; int t [] = new int [n + 1]; random r = new random (); for (int i == 0; i & lt; t.length; i ++) {t [i] = 0; // start it for zero} Int m = 0; // to begin it as well (int i = 0; i & lt; a.length; i ++) {m = r.nextInt (n); // If the random element between 0 and n (t [m] == 1) {// I have this problem i repeat element / repeat of the case occurs As long as these steps repeat, there will be no different numbers. Else {t [m] = 1; x [i] = m;}}  

my problem concret: if T [m] == 1. This means that this element is already already, so I want to create a new number, but the problem is that the numbers will not be generated because if I == 0 and Dup Duplicate the element and we write again it needs like goto to repeat I will switch to I == 1. Or:

 for  (int i = 0; i & lt; x.length; i ++) {loop: m = r.nextInt (n); If (x [m] == 1) {current loop; } And {x [m] = 1; A [i] = m; to continue; Continue on // i = 1 and on the next step. }}  

I want this code in java.

It seems that you want a random sample algorithm set to {0,1,2,3} .., n-1} want to be able to choose random items.

See, where I wrote 5 efficient algorithms for random sampling.

The following is the implementation of Floyd, which can be useful in your case:

  Private static random rnd = new random (); ... set the public stable & lt; Integer & gt; RandomSample (int n, int m) {hashaseet & lt; Integer & gt; Res = new hashset & lt; Integer & gt; (M); For (int i = n - m; i & lt; n; i ++) {int item = rnd.nextInt (i + 1); If res.contains (items) res.add (i); Else res.add (item); } Return Ridge; }  

Comments