java实现二维数组随机生成数并保证只有一个数的次数最多
以下是一种可能的实现:
import java.util.Random;
public class RandomArray {
public static void main(String[] args) {
int[][] arr = generateArray(5, 5, 20);
printArray(arr);
}
public static int[][] generateArray(int rows, int cols, int max) {
int[][] arr = new int[rows][cols];
Random random = new Random();
int maxCount = rows * cols / 2; // 最多出现次数
int[] count = new int[max + 1]; // 记录每个数出现的次数
// 随机生成二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int num = random.nextInt(max + 1);
arr[i][j] = num;
count[num]++;
}
}
// 找出出现次数最多的数
int maxNum = 0;
int maxCountNum = 0;
for (int i = 0; i <= max; i++) {
if (count[i] > maxCountNum) {
maxNum = i;
maxCountNum = count[i];
}
}
// 如果有多个数出现次数相同,则随机选一个数减少出现次数
boolean flag = true;
while (flag) {
flag = false;
for (int i = 0; i <= max; i++) {
if (count[i] == maxCountNum && i != maxNum) {
int row = random.nextInt(rows);
int col = random.nextInt(cols);
if (arr[row][col] == i) {
arr[row][col] = random.nextInt(max + 1);
count[i]--;
count[arr[row][col]]++;
flag = true;
}
}
}
}
return arr;
}
public static void printArray(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
首先,我们定义了一个 generateArray 函数,它接受三个参数:行数、列数和最大值。函数会随机生成一个二维数组,并保证只有一个数的次数最多。生成过程中,我们使用了一个 count 数组记录每个数出现的次数,然后找出出现次数最多的数。如果有多个数出现次数相同,我们会随机选一个数减少出现次数,直到只有一个数的出现次数最多为止。
随机数的生成我们使用了 java.util.Random 类。生成过程中,我们使用了两层循环遍历二维数组,并在内层循环中生成随机数。如果生成的随机数等于出现次数最多的数,我们就将它随机修改为另一个数。
最后,我们定义了一个 printArray 函数用于打印二维数组。你可以在主函数中调用 generateArray 函数生成一个二维数组,并使用 printArray 函数打印出来
原文地址: https://www.cveoy.top/t/topic/hiEF 著作权归作者所有。请勿转载和采集!