Zobrist Hash in Kotlin by the example of tic-tac-toe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlin.math.pow | |
| import kotlin.random.Random | |
| // Article: https://medium.com/@larswaechter/zobrist-hashing-305c6c3c54d0 | |
| /* | |
| * Build the Zobrist table with random numbers. | |
| * For 9 cells and 2 players we need 18 random numbers. | |
| */ | |
| fun buildZobristTable(): Array<Array<Long>> { | |
| val table = Array(2) { Array(9) { 0L } } | |
| for (i in 0..1) | |
| for (k in 0..8) | |
| table[i][k] = Random.nextLong(2F.pow(64).toLong()) | |
| return table | |
| } | |
| val table = buildZobristTable() | |
| /* | |
| * Player 1 = X => index 0 in table | |
| * Player 2 = O => index 1 in table | |
| * | |
| * X . O | |
| * X . . | |
| * . . . | |
| */ | |
| val board = arrayOf(1, 0, 2, 1, 0, 0, 0, 0, 0) | |
| var zobristHash = 0L | |
| // Generate Zobrist hash | |
| for(i in board.indices) | |
| if(board[i] != 0) | |
| zobristHash = zobristHash xor table[board[i] - 1][i] | |
| println(zobristHash) | |
| /* | |
| * Player 2 (O) plays in cell #1 | |
| * | |
| * X O O | |
| * X . . | |
| * . . . | |
| */ | |
| val board2 = arrayOf(1, 2, 2, 1, 0, 0, 0, 0, 0) | |
| // We use the old zobrist hash and take the key of cell #1 for player 2 to calc the new one | |
| val zobristHash2 = zobristHash xor table[1][1] | |
| println(zobristHash2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment