0

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

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

4

2 回答 2

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

请注意:由于所有数字都是可能的,因此会有一些以零开头的值,例如“0012861542”

于 2013-07-20T12:23:45.713 回答
0
byte[] Results = new byte[n]
do
{
    yourCryptoServiceProvider.GetBytes(Results);
}
while (!Results.Distinct().SequenceEqual(Results))
于 2013-07-20T12:10:21.290 回答