User Tools

Site Tools


notes:csharp:random

Random Numbers in C#

Generate random numbers by scaling and shifting: n = a + rand() % b

  • a is the shifting value (the first number in the desired range)
  • b is the scaling factor (the width of the desired range) b = UpperRange - LowerRange + 1

Any public static members of the Random type are thread safe. Any instance members are not guaranteed to be thread safe.

Example: Use the System.Random class:

// Create a random number generator.
Random rnd = new Random();
 
// Generate a value [0 ; Int32.MaxValue]
int num = rnd.Next();
 
// Scaling: generate a value [0 ; 5]
int num = rnd.Next(6);
 
// Scaling and shifting: generate a value [1 ; 6]
int num = rnd.Next(1, 7);

Example: Generate three random numbers (bytes) and insert them into a byte[] array:

Random rnd = new Random();
byte[] rgb = new byte[3];
 
// Populate rgb[0], rgb[1], and rgb[2] with random numbers.
rnd.NextBytes(rgb);

Example: A helper class for generating random numbers:

class RandomHelper
{
    private Random rnd = new Random();
 
    #region Singleton
    private static RandomHelper instance;
    public static RandomHelper Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new RandomHelper();
            }
            return instance;
        }
    }
 
    private RandomHelper() { }
    #endregion
 
 
    // Returns true or false.
    public bool GetTrueOrFalse()
    {
        return (rnd.Next(2) == 0);
    }
 
    // Returns a random integer [0; n-1]
    public int GetInt(int n)
    {
        return rnd.Next(n);
    }
 
    // Returns a random float [0.0; f)
    public float GetFloat(float f)
    {
        return (float)rnd.NextDouble() * f;
    }
 
    // Returns a random float [f1; f2)
    public float GetFloat(float f1, float f2)
    {
        return (f1 + (float)rnd.NextDouble() * (f2 - f1));
    }
 
    // Populates an array uniformly with floats.
    public float[] PopulateFloatArrayUniformly(float segment, float[] arr)
    {
        float unitSegment = segment / (float)arr.Length;
 
        for (int i = 0; i < arr.Length; i++)
        {
            float begin = i * unitSegment;
            float end = begin + unitSegment;
            arr[i] = GetFloat(begin, end);
        }
 
        return arr;
    }
}
 
...
 
// Example #1
float x = RandomHelper.Instance.GetFloat(10.0f);
 
// Example #2
int i = RandomHelper.Instance.GetInt(5);
 
// Example #3
float[] arr = new float[10];
RandomHelper.Instance.PopulateFloatArrayUniformly(15.0f, arr);
 
// Example #4
float f = RandomHelper.Instance.GetFloat(3.0f, 9.0f);
 
// Example #5
string s = (RandomHelper.Instance.GetTrueOrFalse() ? "T" : "F");

Example: Cryptographically strong random number generator System.Security.Cryptography.RandomNumberGenerator.

The Random class does not generate cryptographically unique random numbers. It generates a sequence of random numbers that are dependent on a seed. The same sequence gets generated for the same seed. The default constructor of the Random class uses a time-dependent seed. The RandomNumberGenerator class generates cryptographically unique random numbers.

// Fill a byte array with random numbers.
var rand = System.Security.Cryptography.RandomNumberGenerator.Create();
byte[] arr1 = new byte[32];
rand.GetBytes(arr1); 
 
// Obtain an integer.
byte[] arr2 = new byte[4];
rand.GetBytes(arr2);
int n = BitConverter.ToInt32(arr2, 0);
notes/csharp/random.txt · Last modified: 2016/12/13 by admin