Skip to content

Instantly share code, notes, and snippets.

@futurity75
Created April 12, 2017 08:57
Show Gist options
  • Select an option

  • Save futurity75/0f9509ddc825a11e77b7dffe989cf3df to your computer and use it in GitHub Desktop.

Select an option

Save futurity75/0f9509ddc825a11e77b7dffe989cf3df to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
// by single thread only
static class RandomUtil
{
private static System.Random m_random = new System.Random();
public static int Random(int min, int max)
{
return m_random.Next(min, max);
}
public static float Random(float min, float max)
{
return (float)Random((double) min, (double) max);
}
public static double Random(double min, double max)
{
return m_random.NextDouble() * (max - min) + min;
}
public static T Random<T>(T[] array)
{
if (null == array)
{
return default(T);
}
return array[Random(0, array.Length)];
}
public static T Random<T>(List<T> list)
{
if (null == list || list.Count == 0)
{
return default(T);
}
return list[Random(0, list.Count)];
}
public static void Shuffle<T>(this IList<T> list)
{
if (null == list)
{
return;
}
int n = list.Count;
System.Random rnd = new System.Random();
while (n > 1)
{
int k = (rnd.Next(0, n) % n);
n--;
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment