使用RNGCryptoServiceProvider生成范围为0到n的随机数列表

本文关键字:随机数 列表 RNGCryptoServiceProvider 范围 使用 | 更新日期: 2023-09-27 18:24:14

如何使用RNGCryptoServiceProvider 在c#中创建不重复的随机数列表

我想在范围内,例如0到n个数字?

使用RNGCryptoServiceProvider生成范围为0到n的随机数列表

编辑:如果问题是用给定数量的数字,解决方案可以是一个数字一个数字地组装值:

static RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
public static int NextRandomDigit() {
  Byte[] bytes = new Byte[1];
  while (true) {
    provider.GetBytes(bytes);
    // since GetBytes returns value in a range of [0..255], we should skip [250..255]
    // in order to value % 10 being uniformly distributed
    if (bytes[0] >= 250)
      continue;
    return bytes[0] % 10;
  }
}
// Constructing long digit by digit
// Assuming that numberOfDigits is small enough (18 or less) 
// for returning value being of type long
public static long NextRandomLong(int numberOfDigits) {
  long result = 0;
  for (int i = 0; i < numberOfDigits; ++i)
    result = result * 10 + NextRandomDigit();
  return result;
}
// Constructing number in String representation digit by digit
public static String NextRandomString(int numberOfDigits) {
  StringBuilder Sb = new StringBuilder();
  for (int i = 0; i < numberOfDigits; ++i)
    Sb.Append((Char) ('0' + NextRandomDigit()));
  return Sb.ToString();
}

小心:由于所有数字的可能性都一样以零开头的值,如"0012861542"

byte[] Results = new byte[n]
do
{
    yourCryptoServiceProvider.GetBytes(Results);
}
while (!Results.Distinct().SequenceEqual(Results))