您能帮我找到一种方法,随机数组?例如:
Can you help me to find a way to randomize arrays? E.g.:
int[] arrayInt = { 1, 2, 3, 4, 5, 6, 7 };随机后,结果应该被存储在另一个阵列
after randomizing, the result should be stored in another array.
当你再次随机它应该与存储在第二数组中的值进行比较,如果该值存在程序必须重新随机。
And when you randomize again it should be compared with the values stored in the second array, if that value exist the program must randomize again.
推荐答案下面是使用方法的 Enumerable.OrderBy 以输入阵列具有的随机变量。生成新的序列后,它会与 SequenceEqual :
Here's an approach using Enumerable.OrderBy to order the input-array with a random variable. After the new sequence is generated it'll be compared with the input array with 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(); }此例 - code产生一个被添加到列表10新阵列。它确保了新阵列对previous 1不同:
This example-code generates 10 new arrays which are added to a List. It is ensured that the new array is different to the previous one:
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); }演示