diff --git a/TheSquid.Numerics.Extensions.Tests/NextBigIntegerExtensionTests.cs b/TheSquid.Numerics.Extensions.Tests/NextBigIntegerExtensionTests.cs index 2052841..ee0a5e5 100644 --- a/TheSquid.Numerics.Extensions.Tests/NextBigIntegerExtensionTests.cs +++ b/TheSquid.Numerics.Extensions.Tests/NextBigIntegerExtensionTests.cs @@ -17,7 +17,7 @@ public class NextBigIntegerExtensionTests [DataRow(10000, 100)] [DataRow(100000, 10)] [DataRow(1000000, 1)] - public void NextBigIntegerRandomTest(int iterationsCount, int borderValueLength) + public void NextBigIntegerRandomRangeTest(int iterationsCount, int borderValueLength) { var random = new Random(DateTime.Now.Millisecond); @@ -50,5 +50,41 @@ public void NextBigIntegerRandomTest(int iterationsCount, int borderValueLength) Assert.IsTrue(result <= max, message, min, max, result); } } + + /// + /// Checks that any value within a given range can be generated. + /// + [TestMethod] + [DataRow(1000000, 10, 100)] + [DataRow(1000000, 100, 100)] + [DataRow(1000000, 1000, 100)] + public void NextBigIntegerRandomEquiprobabilityTest(int iterationsCount, int randomRangeSize, int maxDigitsCount) + { + var random = new Random(DateTime.Now.Millisecond); + var maxValueRaw = new StringBuilder(random.Next(1, 10).ToString(), maxDigitsCount); + + for (int i = 1; i < maxDigitsCount; ++i) + { + maxValueRaw.Append(random.Next(0, 10)); + } + + var maxValue = BigInteger.Parse(maxValueRaw.ToString()); + var minValue = maxValue - randomRangeSize + 1; + var resultCounter = new int[randomRangeSize]; + + for (int i = 0; i < iterationsCount; ++i) + { + var result = random.NextBigInteger(minValue, maxValue); + var index = (int)(result - minValue); + ++resultCounter[index]; + } + + const string message = "value={0}, count={1}"; + + for (int i = 0; i < randomRangeSize; ++i) + { + Assert.IsTrue(resultCounter[i] > 0, message, i + minValue, resultCounter[i]); + } + } } } \ No newline at end of file diff --git a/TheSquid.Numerics.Extensions/NextBigIntegerExtension.cs b/TheSquid.Numerics.Extensions/NextBigIntegerExtension.cs index e4315d2..535ab36 100644 --- a/TheSquid.Numerics.Extensions/NextBigIntegerExtension.cs +++ b/TheSquid.Numerics.Extensions/NextBigIntegerExtension.cs @@ -32,12 +32,13 @@ public static BigInteger NextBigInteger(this Random random, BigInteger min, BigI const string maxCannotBeLessMessage = "Max value can not be less then min value."; if (max < min) throw new ArgumentOutOfRangeException(maxCannotBeLessMessage); var residual = max - min; + if (residual == 0) return max; var buffer = residual.ToByteArray(); random.NextBytes(buffer); var multiplier = new BigInteger(buffer); - var addendum = residual & multiplier; - if (addendum < 0) addendum *= -1; - return min + addendum; + if (multiplier < 0) multiplier *= -1; + if (multiplier > residual) multiplier %= residual; + return min + multiplier; } } } \ No newline at end of file