Created
December 6, 2018 10:18
-
-
Save ibrahimatay/0e9db71fcae754cff20fe504c7b74247 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| public static class RandomGenerator | |
| { | |
| private static readonly RandomNumberGenerator generator = RandomNumberGenerator.Create(); | |
| public static int GetNext() | |
| { | |
| byte[] rndArray = new byte[4]; | |
| generator.GetBytes(rndArray); | |
| return BitConverter.ToInt32(rndArray, 0); | |
| } | |
| public static int GetNext(int minValue, int maxValue) | |
| { | |
| if (maxValue < minValue) | |
| throw new InvalidOperationException("maxValue has to be greater than minValue"); | |
| byte[] rndArray = new byte[4]; | |
| generator.GetBytes(rndArray); | |
| int randomNumber = BitConverter.ToInt32(rndArray, 0); | |
| var mod = Math.Abs(randomNumber) % (maxValue - minValue + 1); | |
| return minValue + mod; | |
| } | |
| public static uint GetNextUnsigned() | |
| { | |
| byte[] rndArray = new byte[4]; | |
| generator.GetBytes(rndArray); | |
| return BitConverter.ToUInt32(rndArray, 0); | |
| } | |
| public static uint GetNextUnsigned(uint minValue, uint maxValue) | |
| { | |
| if (maxValue < minValue) | |
| throw new InvalidOperationException("maxValue has to be greater than minValue"); | |
| byte[] rndArray = new byte[4]; | |
| generator.GetBytes(rndArray); | |
| return minValue + (BitConverter.ToUInt32(rndArray, 0) % (maxValue - minValue + 1)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment