以这种特定的方式洗牌数组

本文关键字:方式洗 数组 | 更新日期: 2023-09-27 18:07:30

我想做的是在每次加载控制台应用程序时洗牌下面的数组。例如,蝙蝠侠可以在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;

怎么做?

以这种特定的方式洗牌数组

使用list和这个扩展方法:

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();
    }
}
        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)];
        }

这会给你指明正确的方向。