I'm building a Reversi player using the standard alpha beta pruning search algorithm. I'm trying to add a translation table to store previously calculated nodes in the search tree. So I need to hash a 2 dimensional array representing the game board (the state) and store a value for that.
I can't come up with anything better than a double for loop iterating over my arrays and adding all values together multiplying them with the offsets to get unique hash values.
@Override
public int hashCode() {
if (dirtyHash) {
int hash = 0;
for (int i = 0; i < Board.SIZEX; i++)
for (int j = 0; j < Board.SIZEY; j++)
hash += board[i][j] * (i + Board.SIZEY * j);
hashValue = hash;
dirtyHash = false;
}
return hashValue;
}
I suspect there must be a much smarter way to do this? Anyone got any ideas?
A 2D array is just a bidimensional grid of objects, an HashMap is a special kind of associative array (called also dictionary or map) which associates generic keys to generic values.
A two-dimensional array in C can be thought of as a matrix with rows and columns. The general syntax used to declare a two-dimensional array is: A two-dimensional array is an array of several one-dimensional arrays. Following is an array with five rows, each row has three columns: int my_array[5][3];
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.
I would use java standard library as a first try:
int hash = java.util.Arrays.deepHashCode( board );
Once everything works well, profile your whole app, to check if the hashcode computation is really a performance bottleneck.
If you want to handle this yourself here is one way you could do it.
There are three values for each cell on the board: empty, black, white. That means you can use two bits per cell on the board. And since the board is 8x8 or 64 cells, you can encode the board in two long
primitives. Maybe one of them tells you whether a particular cell is empty, and if it's not, the other tells you its color.
You do not even need to convert this representation into a 2D array. You can use bitwise operators on the long
s directly in your methods to work with the board.
The hash value could then be the XOR of the two long
s, or something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With