C#实现不用随机函数(Random)的洗牌算法
代码不多,先看效果:
类代码:
1 static class ShuffleCards 2 { 3 private static int lastHash = 0; 4 public static void Work(byte[] cards) 5 { 6 if (lastHash == 0) 7 lastHash = System.Environment.TickCount; 8 int len = cards.Length - 2; 9 int mod = 0; 10 byte temp = 0; 11 for (int i = cards.Length - 1; i >= 0 && len>0; i--) 12 { 13 lastHash = (lastHash << 5) - lastHash + i; 14 mod = lastHash < 0 ? lastHash % len * (-1) : lastHash % len; 15 temp = cards[mod]; 16 cards[mod] = cards[i]; 17 cards[i] = temp; 18 len--; 19 } 20 } 21 }
测试代码:
1 //16张牌0~F 2 byte[] cards = new byte[16]; 3 //洗上99次 4 for (int j = 0; j < 100; j++) 5 { 6 //每次都初始化顺序为 0~F 7 for (int i = 0; i < cards.Length; i++) 8 cards[i] = (byte)i; 9 //洗牌调用 10 ShuffleCards.Work(cards); 11 StringBuilder ret = new StringBuilder(); 12 //输出 13 for (int i = 0; i < cards.Length; i++) 14 ret.Append(cards[i].ToString("X") + " "); 15 Console.WriteLine(j.ToString()+" > "+ ret.ToString()); 16 } 17 Console.ReadLine();
分享是追求进步的态度