随机对象将自己分配给多个阵列位置

时间:2011-03-06 23:50:17

标签: java random

        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);
        }

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

/ edit here是类

的构造函数
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);
    }

1 个答案:

答案 0 :(得分:1)

当你声明easy1是一个新的Integer 2D数组时,你说easy1是对1个2D数组对象的引用。

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

我宁愿将此行更改为:

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

这有意义吗?