I've written a class called PuzzleBoard that represents an nxn board. I will be keeping several PuzzleBoard objects in a HashSet, so I have to overwrite the 'int hashCode()' method.
Below are the fields of my class:
private int N;
private int[][] puzzle;
private int blankCellX;
private int blankCellY;
private int cost;
What Eclipse automatically generated for me was:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + N;
result = prime * result + blankCellX;
result = prime * result + blankCellY;
result = prime * result + cost;
result = prime * result + Arrays.hashCode(puzzle);
return result;
}
Thinking that this method doesn't take into account the contents of the 2-d array, I changed it into this:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + N;
result = prime * result + blankCellX;
result = prime * result + blankCellY;
result = prime * result + cost;
for (int i = 0; i < N; ++i)
result = prime * result + Arrays.hashCode(puzzle[i]);
return result;
}
However, the problem with this method is that it takes too long to complete: O(N^2) Furthermore; the 'result' variable is very likely to overflow.
Now, my question is, how do I write an efficient hash method that doesn't take too long to complete. Moreover; inserting or searching an object in the HashSet should be efficient (near constant time).
In the worst case, N will be 10 and the HashSet will contain ~1000 PuzzleBoards.
Why am I doing all this? I'm implementing a solution for the N-Puzzle problem by using the A* algorithm. So in some phase of the algorithm, given the current node (configuration of the board), I'm moving the blank cell up, down, right or left to generate new child nodes. Because of this, puzzle configurations differ usually by 1 or 2 cells. I'm storing all the explored nodes in a HashSet.
Thanks in advance =)