Reputation: 713
While the title is not as descriptive as I hope for it to be. I'll explain the problem further in depth here. If it helps, this question is in relation to a simple Sudoku game.
Suppose we have a 2D array of size size containing some object(s). The object will contain some value and a set containing possible values this object's value can inherit.
Suppose the grid has been filled already and it passes the initial conditions of a Sudoku game (such as no two rows or two columns can contain the same value). Now we have to set the possible values for each object.
This is where I run into the problem. My approach goes as following:
When I attempt to print all object's set, it returns an empty set. When attempting to debug this code, I realized that for some reason values are being removed from all objects and not just the objects with the same row and same column.
Below is the code.
public class Cell {
public int value;
public Set<Integer> possible;
public Cell(int value) {
this.value = value;
this.possible = new HashSet<>();
}
}
// In main class.
int size = 4;
Cell[][] grid = new Cell[size][size];
Set<Integer> possible = new HashSet<>();
possible.add(1);
possible.add(2);
possible.add(3);
possible.add(4);
String[] sample = {"1..2", "..4.", ".1..", "..3."};
for(int row = 0; row < size; row++){
for(int col = 0; col < size; col++){
grid[row][col] = new Cell(Character.getNumericValue(sample[row].charAt(col)));
grid[row][col].possible = possible;
}
}
// Loop to remove value from possible values of all object's with the same row and
// all the object's with the same column.
for(int row = 0; row < size; row++){
for(int col = 0; col < size; col++){
value = grid[row][col].value;
// This loop starts at the specified row or column and removes value from
// all sets with the same row and all sets with the same column.
for(int index = 0; index < size; index++){
grid[row][index].possible.remove(value);
grid[index][col].possible.remove(value);
}
}
}
Upvotes: 0
Views: 74
Reputation: 51034
The mistake is in your code which tries to allocate the sets:
Set<Integer> possible = new HashSet<>();
// ...
for(int row = 0; row < size; row++){
for(int col = 0; col < size; col++){
// ...
grid[row][col].possible = possible;
}
}
You have created one set, and you are assigning it to every cell; so every Cell
object holds a reference to the same set. When you remove a number from that set, it's gone from that set - for every cell, because there aren't any other sets now. The reason the grid later seems to have 16 empty sets is because it actually just has 16 references to the same empty set; you removed all four numbers from it, albeit via different references.
In your Cell
constructor, you assign this.possible = new HashSet<>();
. Instead of overwriting that reference to the possible
set in the loop, write it like this:
grid[row][col].possible.addAll(possible);
Then you will still have a different set for each cell, and they can hold different contents.
Upvotes: 1