C#實現(xiàn)洗牌算法
更新時間:2015年03月23日 11:25:43 投稿:hebedich
洗牌算法的要求是這樣的:將N個數(shù)亂序后輸出.由于和撲克牌的洗牌過程比較相似所以我也就稱為洗牌算法了.很多地方都不自覺的需要這個算法的支持.也可以將這個算法擴展為從N個數(shù)中取出M個不重復的數(shù)(0<M<=N).今天我們看下如何用C#來實現(xiàn)
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 };
//創(chuàng)建一個臨時的撲克牌組
int[] newCards = new Card[54];
//bool變量數(shù)組
bool[] assigned = new bool[54];
Random sourceGen = new Random();
for (int i = 0; i < 54; i++)
{
int destCard = 0; //隨機數(shù)保存空間
bool foundCard = false;
while (foundCard == false)
{
//生成一個0到54之間的隨機數(shù)
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
相比一下,第三個更簡單,更高效!
以上就是本文給大家分享的洗牌算法的全部內(nèi)容了,希望大家能夠喜歡。
相關文章
C# 字符串與unicode互相轉(zhuǎn)換實戰(zhàn)案例
這篇文章主要介紹了C# 字符串與unicode互相轉(zhuǎn)換實戰(zhàn)案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
C#判斷頁面中的多個文本框輸入值是否有重復的實現(xiàn)方法
這篇文章主要介紹了C#判斷頁面中的多個文本框輸入值是否有重復的實現(xiàn)方法,是一個非常簡單實用的技巧,需要的朋友可以參考下2014-10-10
C#中LINQ的Select與SelectMany函數(shù)使用
這篇文章主要介紹了C#中LINQ的Select與SelectMany函數(shù)使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
Unity3D Shader實現(xiàn)動態(tài)星空
這篇文章主要為大家詳細介紹了Unity3D Shader實現(xiàn)動態(tài)星空,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-04-04
基于mvc5+ef6+Bootstrap框架實現(xiàn)身份驗證和權(quán)限管理
最近剛做完一個項目,項目架構(gòu)師使用mvc5+ef6+Bootstrap,用的是vs2015,數(shù)據(jù)庫是sql server2014。下面小編把mvc5+ef6+Bootstrap項目心得之身份驗證和權(quán)限管理模塊的實現(xiàn)思路分享給大家,需要的朋友可以參考下2016-06-06

