ImportJava.util.HashSet; Public classRandomnumbers {/*** N non-repeating numbers in a randomly specified range use the HashSet feature to store only different values * *@parammin * Specify the range minimum value *@paramMax * Specify range Max *@paramn * Number of random numbers *@paramhashset<integer> * Set random number result set*/ Public Static voidRandomset (intMinintMaxintN, hashset<integer>set) { if(n > (max-min + 1) | | Max <min) { return; } for(inti = 0; I < n; i++) { //Call the Math.random () method intnum = (int) (Math.random () * (max-min)) +min; Set.add (num);//deposit different numbers into HashSet } intSetSize =set.size (); //if the number of deposits is less than the number of specified builds, the call recursively regenerates the remaining number of random numbers so that it loops until the specified size is reached if(SetSize <N) {/*** Why the following line is commented out, to tell the truth almighty mother everywhere is this code * but if that is not sure to be able to determine the number of corresponding values * The big boys still look carefully first , N-setsize is just the number of non-generated, and how to play if you don't generate a different value next time.*/randomset (min, max, n-SetSize, set);//Recursive//randomset (min, Max, n, set);//Recursive } } Public Static voidMain (string[] args) {/*** So that's it , according to your needs to generate the most appropriate value * Example default generated 4-bit random number, from 0 to 999 of course not forget, so it is 8,999 people * But the number can not exceed the range you give, The JVM will explode.*/ intmax = 5;//maximum value of a random number range intmin = 1;//minimum value for the range of random numbers intn = 4;//number of buildshashset<integer> numbers =NewHashset<integer>(); Randomset (min,max,n,numbers); SYSTEM.OUT.PRINTLN (numbers);//feel free to print and look at the effect } }
Generate non-repeating random numbers in Java (according to the HashSet feature)