C# int.MinValue 的随机种子值不可预测

标签 c# random seed

所以我目前正在尝试测试一个使用随机函数的函数。为了测试它,我将种子值传递给 C# Random 函数。 (即系统.随机)

我的测试用例涉及使用 int.MaxValue 和 int.MinValue 进行边界测试。整数的最大值会产生一致的预期结果。但是,当我尝试使用最小值时,下一个会不断产生不可预测的随机结果,因此无法进行测试。

我很好奇这是否是预期的,或者种子没有产生可预测结果的原因是什么。我错过了什么吗?

提前致谢。

编辑:

提供代码供引用。这些方法是数组扩展,我使用它们将数组打乱为随机顺序。我使用随机类来获得不同的结果,并将我的种子作为可选参数传递以允许测试。

public static void Shuffle<T>(this T[] array, int seedValue = -1)
{
   // Create the randomizer that will be needed
   Random random = seedValue >= 0 ? new Random(seedValue) : new Random();

   // Run the algorithm
   for (int i = array.Length - 1; i > 0; i--)
   {
       // Get a random integer with a maximum of i
       int r = random.Next(i);

       // Swap the element at r with the element at i
       array.Swap(r, i);
   }
}

public static void Swap<T>(this T[] array, int indexOne, int indexTwo)
{
    // Check if the indices that we were passed are the same index
    if (indexOne == indexTwo)
    {
        return;
    }

    // Check that the first index is in range
    if (indexOne < 0 || indexOne >= array.Length)
    {
        throw new ArgumentOutOfRangeException("indexOne", "The first index provided is out of the range of the array provided.");
    }

    // Check that the second index is in range
    if (indexTwo < 0 || indexTwo >= array.Length)
    {
        throw new ArgumentOutOfRangeException("indexTwo", "The second index provided is out of the range of the array provided.");
    }

    // Swap the items
    T temp = array[indexOne];
    array[indexOne] = array[indexTwo];
    array[indexTwo] = temp;
}

这些是正在测试的方法。我将最小值传递给 Shuffle 函数。经过对我自己的进一步调查,它似乎具有任何负面值(value)。它似乎产生不一致的结果。我目前正在从事 .NET 2.0 工作。我知道旧版本,但我在 Unity 中工作。

最佳答案

这是你的问题:

Random random = seedValue >= 0 ? new Random(seedValue) : new Random();

如果您传递的种子值小于零,则您根本没有使用它, 因此,很自然地,随机种子是从运行计算机的时钟中选择的。

关于C# int.MinValue 的随机种子值不可预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48365231/

相关文章:

c# - 模型绑定(bind)不适用于 int 数组

基于另一列值的列中的随机数

ruby-on-rails - 如何在 db/seeds 中使用 FactoryBot?

mysql - 使用预设 ID 播种 Rails 数据库

c# - 将 curl 与 Phalanger 结合使用

c# - 如何解决 "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types"Android 错误?

algorithm - 生成一个随机数序列得到并取平均

c++ - 如何编写一个可控的随机数生成器?

java - Windows 操作系统上 java.security.SecureRandom 的种子

c# - WPF 以编程方式在 Viewmodel 类上设置 DataTemplate