如何使用递归 Java 创建二维数组非重复数字



我想使用递归函数来检查非重复 NxM 数组中的数字

public static void main(String[] args) {
int N, M, i, j;
N = (int) (Math.random() * 5 + 3);
M = (int) (Math.random() * 5 + 3);
int matris[][] = new int[N][M];
System.out.println("Setir=" + N);
System.out.println("Sutun=" + M);
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
matris[i][j] = (int) (Math.random() * 900 + 100);
System.out.print(matris[i][j] + " ");    
}
System.out.println(" ");
}
}
public class Main {
static boolean isInitial = true;
static boolean isnChanged = true;
static Integer maxN = null;
static Integer matrix[][];
static List list = new ArrayList<Integer>();
public static void main(String[] args) throws ParseException {
generateMatirx(3, 3);
print2D(matrix);
}
public static Integer[][] generateMatirx(int m, int n) {
if (isInitial) {
matrix = new Integer[m][n];
isInitial = false;
--m;
maxN = --n;
}
matrix[m][n] = checkAndAdd();
if (n > 0) {
isnChanged = true;
--n;
} else {
isnChanged = false;
if (maxN != 0)
n = maxN;
}
if (!isnChanged && m > 0) {
--m;
}
if (n == 0 && m == 0) {
matrix[m][n] = checkAndAdd();
return matrix;
}
return generateMatirx(m, n);
}
public static Integer checkAndAdd() {
Integer integerRand = ThreadLocalRandom.current().nextInt(1, 3);
if (list.contains(integerRand)) {
return checkAndAdd();
} else {
list.add(integerRand);
return integerRand;
}
}
private static void print2D(Integer mat[][]) {
// Loop through all rows
for (Integer[] row : mat)
// converting each row as string
// and then printing in a separate line
System.out.println(Arrays.toString(row));
}

}

您希望在检查期间发生什么?只是为了检查是否有任何重复项目,如果有,则返回 true,如果没有,则返回 false 或其他东西?

最新更新