Skip to content

Instantly share code, notes, and snippets.

@larswaechter
Last active August 2, 2020 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larswaechter/2c007c00904822b68331fe26736d92a8 to your computer and use it in GitHub Desktop.
Save larswaechter/2c007c00904822b68331fe26736d92a8 to your computer and use it in GitHub Desktop.
Zobrist Hash in Kotlin by the example of tic-tac-toe
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