ArrayList <int []>仅显示最后一个数组

1 java combinations arraylist

我正在尝试编写一个"Mastermind"人工智能程序,目前我正在尝试实现一个天真的AI,它可以搜索所有可能的1296种4种栓子和6种颜色的组合.我已经写了以下for循环来打印出所有组合:

int compguess[] = new int[4];
int a, b, c, d;
ArrayList<int[]> combination = new ArrayList<int[]>();
for (int z = 0; z < 6; z++) {
                for (int x = 0; x < 6; x++) {
                    for (int i = 0; i < 6; i++) {
                        for (int k = 0; k < 6; k++) {
                            a = z;
                            b = x;
                            c = i;
                            d = k;
                            compguess[0] = a;
                            compguess[1] = b;
                            compguess[2] = c;
                            compguess[3] = d;
                            combination.add(compguess);
Run Code Online (Sandbox Code Playgroud)

当我System.out.println("combination" + Arrays.toString(combination.get(k)));在最后运行此代码时.这会正确显示组合,但是当我尝试执行以下操作时:

 for(int i=0; i< height; i++){
                int[] temp = combination.get(i);
                for(int j = 0; j < 4 ; j++){
                    state[i][j] = temp[j];
                }
                guess.addActionListener(this);

        }
Run Code Online (Sandbox Code Playgroud)

它只显示最后一个元素(4,4,4,4)40次,而我希望它是(0,0,0,0),(0,0,0,1),(0,0,0) ,2),(0,0,0,3),(0,0,0,4),(0,0,0,5),(0,0,1,0),(0,0,1) ,1),(0,0,1,2),(0,0,1,3)只有10的大小 height

Leo*_*eon 5

问题是你每次都使用相同的数组,导致其中一个更改为全部更改,事实上它们是相同的.只需在最里面的for循环中重新初始化数组:

for (int z = 0; z < 6; z++) {
    for (int x = 0; x < 6; x++) {
        for (int i = 0; i < 6; i++) {
            for (int k = 0; k < 6; k++) {
                compguess = new int[4];
                // rest of your code
Run Code Online (Sandbox Code Playgroud)