有时候希望从一个集合中随机取n个元素不重复
那么就取到这n个数字的索引
public static int[] GetRandomArray(int Number, int minNum, int maxNum)
{
int j;
int[] b = new int[Number];
Random r = new Random(GetRandomSeed());
for (j = 0; j < Number; j++)
{
int i = r.Next(minNum, maxNum + 1);
int num = 0;
for (int k = 0; k < j; k++)
{
if (b[k] == i)
{
num = num + 1;
}
}
if (num == 0)
{
b[j] = i;
}
else
{
j = j - 1;
}
}
return b;
}
注意重置随机数的种子 批量操作时候不会取到一样的
//提高随机数不重复概率的种子
static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
测试:
for (int i = 0; i < 100; i++)
{
string[] result = GetRandomArray(10, 0, 12).Select(t => Convert.ToString(t)).ToArray();
Console.WriteLine(string.Join(",", result));
}
Console.ReadKey();
结果:
public static int[] GetRandomArray(int Number, int minNum, int maxNum)
参数number 取几个索引 minnum 索引的最小值(可取到) maxNum 索引的最大值(可取到的)