C# 洗牌算法

最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。

十年河东十年河西,莫欺少年穷

学无止境,精益求精  

C#洗牌算法如下:

class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            Init(list);
            XiPai(list);
            Print(list);
            DiPai(list);
            list.Clear();

        }

        static void Init(List<string> list)
        {
            list.Add("大王");
            list.Add("小王");
            string[] color = new string[4] { "红桃", "黑桃", "方块", "梅花" };
            string[] cate = new string[] { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", };
            for (int i = 0; i < color.Length; i++)
            {
                for (int j = 0; j < cate.Length; j++)
                {
                    list.Add(color[i] + cate[j]);
                }
            }
        }

        static void Print(List<string> list)
        {
            string[] card = list.ToArray();
            for (int i = 0; i < card.Length; i++)
            {
                Console.WriteLine(card[i]);
            }
            Console.ReadKey();
        }

        static void XiPai(List<string> list)
        {
            int i = list.Count;
            int j;
            if (i == 0)
            {
                return;
            }
            while (--i != 0)
            {
                Random ran = new Random();
                j = ran.Next() % (i + 1);
                string tmp = list[i];
                list[i] = list[j];
                list[j] = tmp;
            }
        }

        static void DiPai(List<string> list)
        {
            Console.WriteLine("以下是底牌");
            Console.WriteLine("*************************");
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(list[list.Count - 1]);
                list.RemoveAt(list.Count - 1);
            }
        }
    }

采用的是交换位置法,程序执行54次。效率还是颇高滴!

@陈卧龙的博客

原文地址:https://www.cnblogs.com/chenwolong/p/Puke.html