【问题标题】:how to create twodimensional arrays non-repeat numbers with recursive java如何使用递归java创建二维数组非重复数字
【发布时间】:2020-03-21 03:55:30
【问题描述】:

我想使用递归函数来检查不重复 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(" ");
    }
}

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow。你预计会发生什么,你在观察什么?

标签: java arrays for-loop recursion return


【解决方案1】:
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));
}

}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-11-22
      • 2017-07-07
      • 2010-11-27
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2020-06-02
      • 2014-02-17
      相关资源
      最近更新 更多