this.size = 9;
        this.populationSize = 10;
        Random rand = new Random();


        Integer[][] easy1 = new Integer[size][size];
        easy1 = this.initializeEasy1(easy1);
        this.sudokuArray = new Sudoku[this.populationSize];
        for (int i = 0; i < this.sudokuArray.length; i++){
            long seed = rand.nextLong();
            System.out.println("" + seed);
            this.sudokuArray[i] = new Sudoku(easy1, this.size, seed);
        }


我正在构建一个进化的数独求解器,并且遇到一个问题,即最后一个数独对象正在覆盖数组中的所有其他对象。我在代码中哪里搞砸了?

/ edit是类的构造函数

public Sudoku(Integer[][] givensGrid, int s, long seed){
    this.size = s;
    this.givens = givensGrid;
    this.grid = this.givens.clone();
    Random rand = new Random(seed);

    System.out.println("Random " + rand.nextInt());
    // step though each row of the grid
    for (int i = 0; i < size; i++){
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers = this.makeNumbers(numbers);

        // step through each column to find the givens and remove from numbers
        for (int j = 0; j < size; j++){
            if (this.grid[i][j] != 0){
                numbers.remove(this.grid[i][j]);
            }
        }
        // go back through the row and assign the numbers randomly
        for (int j = 0; j < size; j++){
            if (this.grid[i][j] == 0){
                int r = rand.nextInt(numbers.size());
                this.grid[i][j] = numbers.get(r);
                numbers.remove(r);
            }
        }
    }
    System.out.println("=============");
    System.out.println(this.toString());
}


这是固定代码

this.size = 9;
    this.populationSize = 10;
    Random rand = new Random();


    Integer[][] easy1 = new Integer[size][size];
    this.sudokuArray = new Sudoku[this.populationSize];
    for (int i = 0; i < this.sudokuArray.length; i++){
        long seed = rand.nextLong();
        easy1 = new Integer[size][size];
        easy1 = this.initializeEasy1(easy1);
        System.out.println("" + seed);
        this.sudokuArray[i] = new Sudoku(easy1, this.size, seed);
    }

最佳答案

当您将easy1声明为新的Integer 2D数组时,就是说easy1是对1个2D数组对象的引用。

然后,您将添加一个引用相同2D数组的新Sudoku对象,因为您将引用传递给了它。因此,您所有的数独对象都仅引用1个2D数组,这可能不是您想要的。

我宁愿将此行更改为:

this.sudokuArray[i] = new Sudoku(new Integer[size][size], size, seed);


那有意义吗?

关于java - 随机对象将自己分配给多个数组位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5214359/

10-11 22:30
查看更多