1

I'm trying to write a "Mastermind" AI program and at the moment I'm trying to implement a naive AI which searches all possible 1296 combination of 4 pegs with 6 colours. I have written up the following for loop to print out all combinations:

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

When I run this code with System.out.println("combination" + Arrays.toString(combination.get(k))); at the end. This displays the combinations properly, however when I try to do the following:

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

        }

It only displays the last element (4,4,4,4) 40 times, instead I want it to be (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) only 10 which is the size of the height

ziggystar
  • 28,410
  • 9
  • 72
  • 124
  • 11
    `combination.add(compguess);` doesn't copy `compguess`. You're putting the same array into the list over and over. Try `combination.add(new int[] { z, x, i, k});` instead. – Andy Turner Apr 03 '17 at 12:35
  • it is working the way I want it too know. THANK YOU SO MUCH! –  Apr 03 '17 at 12:45
  • Possible duplicate of [Why does my ArrayList contain N copies of the last item added to the list?](http://stackoverflow.com/questions/19843506/why-does-my-arraylist-contain-n-copies-of-the-last-item-added-to-the-list) – Tom Apr 03 '17 at 13:13

1 Answers1

5

The problem is that you are using the same array every time, causing a change to one of them to change all, as they are, in fact, the same. Just reinitialize the array in the innermost for loop:

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
Leon
  • 2,926
  • 1
  • 25
  • 34