I’m programming a Sudoku solver just to get myself back into the habit of using Java, and I’m running into a significant inconvenience.
I’m trying to build the necessary classes myself, so my general plan of attack is to have a Puzzle class that consists of an array of Row instances, an array of Column instances, and an array of Sector instances. Each of these classes consists of an array that references the cells within that particular instance. Upon construction, I plan on having the Puzzle class create all 81 Cells, and assign each one to the appropriate Row, Column, and Sector. My question is two-fold:
First, how can I set it up such that each array references the Cells within it, so I can keep them in synch? Just assigning them would create three unique instances of each class, which would have to be synched manually. The alternate situation (unique Cells, each with a reference to a Row, Column, or Sector class) would make iterating through a Row impossible.
Second, how can I automate the process of generating and assigning the Cells? I wanted to do something dynamic just to save the typing and code space – something along the lines of this:
private static final String[] letters{"A", "B", "C", "D", "E", "F", "G", "I"};
for (String letter : Puzzle.letters){
for (int i=1; i<10; i++){
Cell "letter+j" = new Cell();
"letter"[] = "letter+j";
"j"[] = "letter+j";
<Sector Calculation>
"sector"[] = "letter+j";
}
}
Obviously, that sort of thing doesn’t work, but writing out 81 constructions and 243 assignments seems like a really stupid idea.
Thoughts?
I’d simply use a 2 dimensional integer array (in this case
int[9][9]) as data source – then think about which indices indicate a row, a column or a sector. An oo-approach doesn’t quite make sense here, it’s just index-mapping-math that you will have to do.Questions to ask yourself: Does a
Celldo anything else than encapsulating an integer? Does aRow/Column/Sectordo anything else than listing 9 Cells?