I am working on a Sudoku solver right now and currently the cells are represented as a 2d array of size 9x9.
int[][] grid = new int[9][9];
To address the different logic units in the grid (rows, columns, or boxes) I have subclasses to hold an array of size 9 to hold the digits in this unit int[] values = new int[9];
Minimum code:
public class SudokuSolver
{
private abstract class SudokuSet
{
int[] values; //gets initialized in constructor of subclasses
..
}
private class SudokuRow extends SudokuSet
{
SudokuRow(int position)
{
for(int i=0; i<9; i++)
values[i] = grid[position][i];
..
}
..
}
int[][] grid = new int[9][9];
SudokuSolver(int[][] g)
{
grid = g;
..
}
private void insertDigit(int x,int y,int d)
{
grid[y][x] = d;
..
}
}
What I want to achieve is that values
is always up to date with the logically connected parts of grid
. In other words when I call insertDigit and it assigns a value to a position in the grid then I want to have every corresponding values attribute to be updated. So I want to have values
hold references to the data in grid
Of course, I could do keep track of the inserted digit and also insert it manually in each logic unit values
but as each cell appears in exactly 3 units it would be a bit of a bother and not as elegant. Also this project is meant to learn more Java coming from C/C++ so this is a good opportunity to understand how something like this is possible without actual pointers.
According to my research this is not possible with arrays of primitive types because e.g. when assigning values[0] = grid[5][0]
it will actually copy the value. So I am not deadset on using arrays and I am happy to accept a different data structure.
I tried using ArrayList<Integer> because I thought Integers are objects (wrapper class of int), but it seems to not work either.
I tried something like
ArrayList<Integer> myList1 = new ArrayList<Integer>();
myList1.add(0);
myList1.add(1);
ArrayList<Integer> myList2 = new ArrayList<Integer>();
myList2.add(myList1.get(0));
myList1.set(0,5) //--> myList2.get(0) is still 0
Well, when you do myList1.set(0,5)
you are actually setting the content of myList1[0]
to a different object, but myList2[0]
is still pointing to the same object as it was before. You need an object where you can actually change a property, but that's not possible with the Integer
class.
class IWrapper {
public IWrapper(int val){
value = val;
}
public int value;
}
ArrayList<IWrapper> myList1 = new ArrayList<IWrapper>();
ArrayList<IWrapper> myList2 = new ArrayList<IWrapper>();
myList1.set(0, new IWrapper(5));
myList2.set(0, myList1.get(0));
myList1.get(0).value = 3;
System.out.println(myList2.get(0).value);
But the bigger question is, if you want to be myList1
and myList2
to be in sync, why do you not just assign
myList2 = myList1;
This way, all changes you do to myList1
will automatically show up also in myList2
because they are in fact both pointing to the very same object ...