Java is used to generate 100 non repeating Numbers between 1 150
- 2020-06-12 09:02:35
- OfStack
The core code
import java.util.Arrays;
/**
* with Java produce 100 a 1-150 The number of
*/
public class RandomTest {
public static void main(String[] args) {
int[] resultArr = produceNum(1, 150, 100);
for (Integer num : resultArr) {
System.out.println(num);
}
System.out.println("+++++++++++++++++===================+++++++++++++");
// Sort the result array before printing it out
Arrays.sort(resultArr);
for (Integer num : resultArr) {
System.out.println(num);
}
}
/**
* Generate random Numbers
* @param minNum The minimum number
* @param maxNum The largest number
* @param numCount The number of Numbers produced
* @return The result array
*/
public static int[] produceNum(int minNum, int maxNum, int numCount) {
// Into the reference check
// If the number of random Numbers is greater than the range of random number generation; Or the maximum number is less than the minimum number
// Direct return null , indicating that the participation does not meet the requirements
if (numCount > (maxNum - minNum + 1) || maxNum < minNum) {
return null;
}
// An array of results
int[] resultArr = new int[numCount];
// count Record the number of random Numbers generated
int count = 0;
while(count < numCount) {
// Random number generation
int num = (int) (Math.random() * (maxNum - minNum)) + minNum;
// flag Defines whether the random number generated this time is already in the array
boolean flag = true;
// The random number generated in the traversal group
for (int i=0; i<count; i++) {
// Compared to the random number generated this time
if (num == resultArr[i]) {
// If the same value already exists, jump out for Loop, continue to the outer layer while Loop, produce down 1 A random number
flag = false;
break;
}
}
// If the random number generated does not exist in the array, the random number is stored in the array
if (flag) {
resultArr[count] = num;
// The number of random Numbers generated in the array plus 1
count++;
}
}
return resultArr;
}
}
Code reading
1 int num = (int) (Math.random() * (maxNum - minNum)) + minNum;
Math. random() generates random Numbers of type double between 0 and 1
Math.random() * 10 will get a random number between 0 and 10. After turning to int, it will get 0 to 9. If you give Math. random() * 10 + 1, it will be a random number between 1 and 11. If you convert int, it will be 1 to 10.
Here 1 corresponds to the minimum in the program and 11 to the maximum.
This gives us (int) (Math. random() * (maxNum-ES24en)) + minNum for random number generation
2 for (int i=0; i
<
count; i++) {
Since the num generated each time is random, there is no guarantee that the problem will be repeated, so only by comparing it with the number already generated in the existing array, if identical, it will be re-generated, and if different, it will be added to the array.