using System;
using System.Collections.Generic;
using System.Linq;
using Abp.Collections.Extensions;
namespace Abp
{
///
/// A shortcut to use class.
/// Also provides some useful methods.
///
public static class RandomHelper
{
private static readonly Random Rnd = new Random();
///
/// Returns a random number within a specified range.
///
/// The inclusive lower bound of the random number returned.
/// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.
///
/// A 32-bit signed integer greater than or equal to minValue and less than maxValue;
/// that is, the range of return values includes minValue but not maxValue.
/// If minValue equals maxValue, minValue is returned.
///
public static int GetRandom(int minValue, int maxValue)
{
lock (Rnd)
{
return Rnd.Next(minValue, maxValue);
}
}
///
/// Returns a nonnegative random number less than the specified maximum.
///
/// The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to zero.
///
/// A 32-bit signed integer greater than or equal to zero, and less than maxValue;
/// that is, the range of return values ordinarily includes zero but not maxValue.
/// However, if maxValue equals zero, maxValue is returned.
///
public static int GetRandom(int maxValue)
{
lock (Rnd)
{
return Rnd.Next(maxValue);
}
}
///
/// Returns a nonnegative random number.
///
/// A 32-bit signed integer greater than or equal to zero and less than .
public static int GetRandom()
{
lock (Rnd)
{
return Rnd.Next();
}
}
///
/// Gets random of given objects.
///
/// Type of the objects
/// List of object to select a random one
public static T GetRandomOf(params T[] objs)
{
if (objs.IsNullOrEmpty())
{
throw new ArgumentException("objs can not be null or empty!", "objs");
}
return objs[GetRandom(0, objs.Length)];
}
///
/// Generates a randomized list from given enumerable.
///
/// Type of items in the list
/// items
public static List GenerateRandomizedList(IEnumerable items)
{
var currentList = new List(items);
var randomList = new List();
while (currentList.Any())
{
var randomIndex = RandomHelper.GetRandom(0, currentList.Count);
randomList.Add(currentList[randomIndex]);
currentList.RemoveAt(randomIndex);
}
return randomList;
}
}
}