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次。效率還是頗高滴!

@陳卧龍的博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM