随机化一个整数数组

Rev*_*xic 1 c# arrays random

你能帮我找一个随机化数组的方法吗?例如:

int[] arrayInt = { 1, 2, 3, 4, 5, 6, 7 };
Run Code Online (Sandbox Code Playgroud)

随机化后,结果应存储在另一个数组中.

当你再次随机化时,它应该与存储在第二个数组中的值进行比较,如果该值存在,程序必须再次随机化.

Tim*_*ter 7

这是一种用于使用随机变量Enumerable.OrderBy对输入数组进行排序的方法.生成新序列后,它将与输入数组进行比较:SequenceEqual

public static T[] UniqueRandomArray<T>(T[] input, Random rnd)
{
    if (input.Length <= 1) throw new ArgumentException("Input array must have at least two elements, otherwise the output would be the same.", "input");
    IEnumerable<T> rndSeq;
    while (input.SequenceEqual(rndSeq = input.OrderBy(x => rnd.Next())));
    return rndSeq.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

此示例代码生成10个新数组,这些数组将添加到List中.确保新阵列与前一阵列不同:

Random rnd = new Random();
List<int[]> randomArrays = new List<int[]>();
int[] arrayInt1 = { 1, 2, 3, 4, 5, 6, 7 };
randomArrays.Add(arrayInt1);

for (int i = 0; i < 10; i++)
{
    int[] lastArray = randomArrays[randomArrays.Count - 1];
    int[] randomArray = UniqueRandomArray(lastArray, rnd);
    randomArrays.Add(randomArray);
}
Run Code Online (Sandbox Code Playgroud)

演示