Fisher–Yates在C#

时间:2019-05-30 12:49:04

标签: c#

我有一个方法Shuffle,它想返回一组用上述方法显示的随机数,但是这些数字需要以混合格式显示。 第一种方法效果很好,因为在范围集中正确显示了数字,但是该方法Shuffle不会以混合格式返回它们。

示例:

第一个方法返回:1, 2, 3, 4, 5

此方法需要返回2, 1, 4, 5, 3

    public int[] Shuffle(int[] Sequence)
    {
        int[] Array = new int[Sequence.Length];

        for(int s=0; s < Array.Length-1; s++){
           int GenObj = GenerateAnotherNum (0, Array.Length + 1);

            Array[s] = Sequence[GenObj];
            Sequence[GenObj] = Array[s];
        }
        return Sequence;
    }

1 个答案:

答案 0 :(得分:2)

您这里有几个问题:全零数组,范围和交换过程

算法:

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

代码:

id|name
1 |A   
2 |B   
3 |C   

演示:

// probably "static" should be added (depends on GenerateAnotherNum routine)
public int[] Shuffle(int[] Sequence)
{
    // public method's arguments validation
    if (null == Sequence)
        throw new ArgumentNullException(nameof(Sequence));

    // No need in Array if you want to modify Sequence

    for(int s = 0; s < Sequence.Length - 1; s++)
    {
        int GenObj = GenerateAnotherNum(s, Sequence.Length); // pleace, note the range

        // swap procedure: note, var h to store initial Sequence[s] value
        var h = Sequence[s];          
        Sequence[s] = Sequence[GenObj];
        Sequence[GenObj] = h;
    }

    return Sequence;
}

结果:

// Random(0) - we want to reproduce the results in the demo
private static Random random = new Random(0); 

// Let unknown GenerateAnotherNum be a random
private static int GenerateAnotherNum(int from, int to) => random.Next(from, to);

...

int[] array = new int[] { 1, 2, 3, 4, 5 };

string result = string.Join(", ", Shuffle(array));

Console.Write(result);