2

我想做的是每次加载控制台应用程序时都对下面的数组进行洗牌。例如,batman 可能每次都在 'name[0]' 旁边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;

怎么做?

4

2 回答 2

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();
    }
}
于 2013-04-04T18:04:40.267 回答
-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)];
        }

那应该为您指明正确的方向。

于 2013-04-04T18:02:21.977 回答