unsafe static int[] GenerateRandom(int length, int minInclusive, int maxExclusive)
{
var bytes = new byte[length * 4];
var ints = new int[length];
var ratio = uint.MaxValue / (double)(maxExclusive - minInclusive);
using (RandomNumberGenerator generator = RandomNumberGenerator.Create())
{
generator.GetBytes(bytes);
fixed(byte* b = bytes)
{
uint* i = (uint*)b;
for(int j = 0; j < length; j++, i++)
{
ints[j] = minInclusive + (int)(*i / ratio);
}
}
}
return ints;
}
I've run a little test:
var ints = GenerateRandom(1000000, 0, 300);
var groups = ints.GroupBy(x => x).Select(g => new { value = g.Key, count = g.Count() });
var hist = Enumerable.Range(0, 300).Join(groups, x => x, g => g.value, (x, g) => new { value = x, count = g.count }).ToList();
var max = hist.OrderByDescending(x => x.value).First();
var min = hist.First();
And results are quite random across all numbers between 0
and 300
with min.count = 3301
and max.count = 3358
.