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

时间:2013-07-20 12:00:25

标签: c#

如何使用RNGCryptoServiceProvider

在c#中创建无重复的随机数列表

我希望在范围内有例如0到n的数字吗?

2 个答案:

答案 0 :(得分:2)

编辑:如果问题是用给定的数量来构造随机值 数字,解决方案可能是逐位汇总值:

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();
}

小心:因为所有数字都是同样可能的,所以会有 以零(s)开头的值,如“0012861542”

答案 1 :(得分:0)

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