i.Posei's blog

Happiness only real when shared!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

简单快速的洗牌算法

Posted on 2008-02-14 16:35  i.Posei  阅读(2730)  评论(11编辑  收藏  举报
过年的时候跟朋友学了一种新的扑克牌玩法,有瘾了,在网上找了半天没找到这种玩法的单机版,于是决定自己写一个。

洗牌当然就成了第一个要完成的动作了,在网上找了一下,找到一篇园子里一位朋友写的文章(扑克牌的随机发牌程序),看看后,感觉有点麻烦,于是自己写了一个,实在是简单,就不多做解释了。代码如下:

    class Poker
    {
        /// <summary>
        /// 记录54张牌
        /// </summary>
 
        private int[] _cards = new int[54] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 };
       
        public Poker()
        { }

        public void Reshuffle()
        {
            Random ram = new Random();
            int currentIndex;
            int tempValue;

            for (int i = 0; i < 54; i++)
            {
                currentIndex = ram.Next(0, 54 - i);
                tempValue = _cards[currentIndex];
                _cards[currentIndex] = _cards[53 - i];
                _cards[53 - i] = tempValue;
            }
        }
    }

执行Reshuffle()方法后,_cards里的顺序便是新的了。

PS:在文章里怎么添加代码呢?搞忘记了哦,哪位兄弟告诉一声。