In the recent project, we need to generate n unequal random numbers. when implementing this, we can catch up with the construction period. In the project, n is very small (0-100). Thanks to the most intuitive method:
Public static list <integer> randomset (INT num, int threshold) {random = new random (); If (Num> threshold) return NULL; set <integer> randomset = new hashset <integer> (); While (randomset. size () <num) randomset. add (random. nextint (threshold); List <integer> result = new arraylist <integer> (); result. addall (randomset); return result ;}
As long as it is based on the return and return weights of the hashset to reach an unequal random number, but when num is large or num is close to threshold, at this time, the average expectation is relatively large. The complexity of num * threshold * lognum
Other similar methods include using an array to mark whether a number has been marked. Complexity is the same as above
The following describes two methods whose complexity is num and threshold:
Method 1: shuffle. The Code is as follows:
Public static list <integer> random_shuffle (INT num, int thresold) {random RD = new random (); List <integer> result = new arraylist <integer> (thresold ); for (INT I = 0; I <thresold; I ++) result. add (I + 1); For (INT I = thresold; I> 0; I --) Swap (result, I-1, RD. nextint (thresold); return result. sublist (0, num );}
Place an array containing thresold, randomly disrupt the order, and then return the previous num. You can also directly use the collections. Shuffle (list) method. We can see from the source code that the shuffle algorithm is also like this. Time Complexity: Threshold
Method 2: Use two arrays and one array result to store the results. Target is used to store the numbers from 1 to threshold. Each time, a random number r smaller than threshold is removed from the target and placed into the result, at the same time, the number of R and threshold-1 is exchanged in the target, and threshold -- is used to ensure that this number will not be obtained in the future.
The Code is as follows:
Public static list <integer> random_2 (INT num, int thresold) {random RD = new random (); List <integer> Target = new arraylist <integer> (thresold ); for (INT I = 0; I <thresold; I ++) target. add (I + 1); List <integer> result = new arraylist <integer> (); For (INT I = 0; I <num; I ++) {int r = RD. nextint (thresold); result. add (target. get (R); swap (target, R, thresold-1); thresold --;} return result ;}