Last active
January 13, 2016 18:04
-
-
Save Svetomech/93c70236144ea1b5caeb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Security.Cryptography; | |
namespace FDL.Library.Numeric | |
{ | |
public static class RandomNumber | |
{ | |
private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider(); | |
public static int Between(int minimumValue, int maximumValue) | |
{ | |
byte[] randomNumber = new byte[1]; | |
_generator.GetBytes(randomNumber); | |
double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber[0]); | |
// We are using Math.Max, and substracting 0.00000000001, | |
// to ensure "multiplier" will always be between 0.0 and .99999999999 | |
// Otherwise, it's possible for it to be "1", which causes problems in our rounding. | |
double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d); | |
// We need to add one to the range, to allow for the rounding done with Math.Floor | |
int range = maximumValue - minimumValue + 1; | |
double randomValueInRange = Math.Floor(multiplier * range); | |
return (int)(minimumValue + randomValueInRange); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment