随机化整数数组 [英] Randomise an array of integers

查看:156
本文介绍了随机化整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我找到一种方法,随机数组?例如:

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 以输入阵列具有的随机变量。生成新的序列后,它会与 <$ C输入数组进行比较$ C> 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);
}

演示

这篇关于随机化整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆