我想在每次加载控制台应用程序时将下面的数组洗牌。例如,每次蝙蝠侠都可以在name[1]
,name[2]
或name[3]
旁边,而不是'name [0]'。
heroes[] names = new heroes[4];
names[0] = batman;
names[1] = ironman;
names[2] = hulk;
names[3] = flash;
怎么做?
答案 0 :(得分:3)
使用列表和此扩展方法:
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();
}
}
答案 1 :(得分:-2)
heroes[] names = new heroes[4];
names[0] = batman;
names[1] = ironman;
names[2] = hulk;
names[3] = flash;
var rnd = new Random(DateTime.Now.Second);
for (int i = 0; i < heroes.Length; i++)
{
names[i] = heroes[rnd.Next(0, heroes.Length - 1)];
}
这应该指向正确的方向。