欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现洗牌算法

程序员文章站 2023-12-13 10:58:52
c#洗牌算法,简单演示! 算法一、 /// /// 洗牌算法 /// private v...

c#洗牌算法,简单演示!

算法一、

/// <summary>
/// 洗牌算法
/// </summary>
private void test()
{
 int[] icards = new int[54];
 for (int i = 0; i < icards.length; i++)
 {
 icards[i] = i + 1;
 }
 //
 random rand = new random();
 int itarget = 0, icardtemp = 0;
 for (int i = 0; i < icards.length; i++)
 {
 itarget = rand.next(0, icards.length);
 icardtemp = icards[i];
 icards[i] = icards[itarget];
 icards[itarget] = icardtemp;
 }
 
 for (int i = 0; i < icards.length; i++)
 {
 response.write("第" + (i + 1) + "张牌是:" + icards[i] + "<br/>");
 }
}

算法二、

public void shuffle()
  {
   
   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 };
   //创建一个临时的扑克牌组
   int[] newcards = new card[54];
   //bool变量数组
   bool[] assigned = new bool[54];

   random sourcegen = new random();
   for (int i = 0; i < 54; i++)
   {
    int destcard = 0;     //随机数保存空间
    bool foundcard = false;
    while (foundcard == false)
    {
     //生成一个0到54之间的随机数
     destcard = sourcegen.next(54);
     if (assigned[destcard] == false)
     {
      foundcard = true;
     }
    }
    assigned[destcard] = true;
    newcards[destcard] = cards[i];
   }

算法三、

public void reshuffle()
  {
   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 };
   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;
   }
  }

15

相比一下,第三个更简单,更高效!

以上就是本文给大家分享的洗牌算法的全部内容了,希望大家能够喜欢。

上一篇:

下一篇: