所以我目前正在尝试测试一个使用随机函数的函数。为了测试它,我将种子值传递给 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/