40 lines
1.1 KiB
C#
40 lines
1.1 KiB
C#
using System;
|
|
|
|
public static class RandomHelper
|
|
{
|
|
// Single Random instance for the whole app
|
|
private static readonly Random _rand = new Random();
|
|
|
|
// Random integer [min, max] inclusive
|
|
public static int Int(int min, int max)
|
|
{
|
|
return _rand.Next(min, max + 1); // max is inclusive
|
|
}
|
|
|
|
// Random float [min, max)
|
|
public static float Float(float min, float max)
|
|
{
|
|
return (float)(_rand.NextDouble() * (max - min) + min);
|
|
}
|
|
|
|
// Random double [min, max)
|
|
public static double Double(double min, double max)
|
|
{
|
|
return _rand.NextDouble() * (max - min) + min;
|
|
}
|
|
|
|
// Random element from an array
|
|
public static T Choice<T>(T[] array)
|
|
{
|
|
if (array == null || array.Length == 0)
|
|
throw new ArgumentException("Array cannot be null or empty.");
|
|
return array[_rand.Next(array.Length)];
|
|
}
|
|
|
|
// Random enum value
|
|
public static T ChoiceEnum<T>() where T : Enum
|
|
{
|
|
Array values = Enum.GetValues(typeof(T)); // returns System.Array
|
|
return (T)values.GetValue(_rand.Next(values.Length)); // use GetValue
|
|
}
|
|
} |