首页 文章

生成随机的非重复数字二维数组Java

提问于
浏览
1

用户将输入 i (变体)的数字,然后输入 j 的数字(每个变体的元素),最后输入可能的最大值(maxElem) . 使用输入的值,任务是生成非重复的随机数( nonrepeating in a variant, meaning for i ,但数字可能在整个数组期间重复) .

例如,给出输入 3 (i), 5 (j), 9 (maxElem) 的成功输出将是:

4 | 8 | 1 | 7 | 9

3 | 8 | 2 | 4 | 5

2 | 6 | 4 | 8 | 5

您可能会注意到,数字4在整个阵列中重复3次(允许) . 但是,对于 i=0 ,数字4是唯一的 .

请指导我对此代码的更改:

static Scanner sc = new Scanner(System.in);

static int maxElem;

public static void main(String[] args) {

    int[][] greatLoto;

    System.out.println("Of how many variants will the ticket consist?  ");
    int variants = sc.nextInt();

    System.out.println("Of how many elements will the variants consist? ");
    int elements = sc.nextInt();

    System.out.println("Which value should be considered the maximum value? ");
    maxElem = sc.nextInt() + 1;

    greatLoto = new int[variants][elements];

    System.out.println("Initial values: ");
    show(greatLoto);

    System.out.println("Modifying values...");
    modified(greatLoto);

    System.out.println("Newest values: ");
    show(greatLoto);

}

private static void show(int[][] greatLoto) {
    for (int i = 0; i < greatLoto.length; i++) {
        for (int j = 0; j < greatLoto[i].length; j++) {
            System.out.print("|" + greatLoto[i][j] + "|");
        }
        System.out.println("");
    }
    System.out.println("");
}

private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
    for (int i = 0; i < greatLoto.length; i++) {
        for (int j = 0; j < greatLoto[i].length; j++) {

            while (Arrays.asList(greatLoto[i]).contains(r)) {
               r = new Random(System.currentTimeMillis());
            }
            greatLoto[i][j] = r.nextInt(maxElem);;

        }
        System.out.println("");

    }

}

3 回答

  • 0

    这更像是一个注释但是太长了:不要使用random.next()因为它会强制你检查唯一性 . 而是使用有效值填充列表并将其随机化:

    List<Integer> values = new ArrayList<> ();
    for (int i = 1; i <= max; i++) values.add(i);
    Collections.shuffle(values);
    

    然后,您可以简单地迭代值并获取j个第一个数字 .

    请注意,如果j显着大于i,使用随机方法可能会更有效 .

  • 0

    最小的变化是:

    private static void modified(int[][] greatLoto) {
    Random r = new Random(System.currentTimeMillis());
        for (int i = 0; i < greatLoto.length; i++) {
            for (int j = 0; j < greatLoto[i].length; j++) {
                do {
                    greatLoto[i][j] = r.nextInt(maxElem);
                } while (Arrays.asList(greatLoto[i]).contains(greatLoto[i][j]));    
            }
            System.out.println("");
        }
    
    }
    

    但是有更优雅(但难以编码)的方法来生成唯一的随机数而不丢弃重复 .

  • 3

    你需要三个循环:

    Loop_1: 构建一个大小为 j 的数组,并对此数组的每个字段使用Loop_1B .

    Loop_1B: 使用 r.nextInt(maxElem)+1; 生成一个int(它必须是 +1 ,因为 nextInt() 仅包含0和指定的值) . 然后检查数字是否已在数组中使用,如果是,则再次运行此循环 .

    Loop_2: 重复循环_1707016_次 .

相关问题