使用列表,該擴展方法:
public static class ListExtensions
{
/// <summary>
/// Shuffle algorithm as seen on page 32 in the book "Algorithms" (4th edition) by Robert Sedgewick
/// </summary>
public static void Shuffle<T>(this IList<T> source)
{
var n = source.Count;
for (var i = 0; i < n; i++)
{
// Exchange a[i] with random element in a[i..n-1]
var r = i + RandomProvider.Instance.Next(0, n - i);
var temp = source[i];
source[i] = source[r];
source[r] = temp;
}
}
}
public static class RandomProvider
{
[ThreadStatic]
public static readonly Random Instance;
static RandomProvider()
{
Instance = new Random();
}
}
你可能使用[費雪耶茨隨機播放/隨機播放克努特(http://en.wikipedia.org/wiki/Fisher%E2%80% 93Yates_shuffle)。 [這](http://www.dotnetperls.com/fisher-yates-shuffle)是一個C#的實現,但應該有一個地方的夫婦,如果你做一個搜索.... – nkvu 2013-04-04 18:02:39
傑瑞巴特勒,我已經刪除所有「謝謝你的提示」/「我正在學習」這篇文章......但我沒有看到關於你洗牌的任何「具體」內容。如果你喜歡,隨時可以恢復我的修改,但一定要解釋你需要什麼「特定」的方式來洗牌元素。否則它是非常流行的問題的重複(上面)。 – 2013-04-04 18:09:51