保存棋局状态——Zobrist Hash算法

作者:追风剑情 发布于:2017-6-11 22:20 分类:Algorithms

参考博客:http://www.cnblogs.com/IThaitian/p/3616507.html

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ZobristTest
  8. {
  9. /// <summary>
  10. /// Zobrist Hash算法是专门用来求当前棋局的Hash算法。
  11. /// 对于复杂的棋类状态值用64位减少hash冲突。简单棋类状态值用32位即可。
  12. /// </summary>
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. int hash = 0;
  18. int hash1 = 0;
  19. //定义一个四个格子的棋盘,并为每个格子赋上状态值。
  20. int[] board = new int[4] { 12, 35, 68, 89 }; //棋盘初始状态
  21. int[] board1 = new int[4] { 12, 20, 68, 89 }; //棋盘的第2个格子状态变化了
  22. //求board棋盘hash值
  23. for (int i = 0; i < board.Length; i++)
  24. {
  25. hash ^= board[i];
  26. }
  27. Console.WriteLine("棋盘初始状态Hash: "+hash);
  28.  
  29. //------------------------------------------------
  30. //笨办法求新棋局状态
  31. //棋盘状态发生变化后重新计算hash值
  32. for (int i = 0; i < board1.Length; i++)
  33. {
  34. hash1 ^= board1[i];
  35. }
  36. Console.WriteLine("棋盘状态Hash1: " + hash1);
  37. //------------------------------------------------
  38.  
  39. //------------------------------------------------
  40. //高效的方法求新棋局状态
  41. //利用Zobrist Hash算法,只需对变化的格子状态重新做一次异或运算就可求得新棋盘的Hash状态。
  42. hash ^= 35;//与变化格子的原来状态值做一次异或运算
  43. hash ^= 20;//与变化格子的新状态值做一次异或运算
  44. Console.WriteLine("棋盘状态hash: " + hash);
  45. //------------------------------------------------
  46.  
  47. Console.ReadKey();
  48. }
  49. }
  50. }


运行测试

11111.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号