c# - Converting random bytes to integers within a specified range -


i trying write function uses default randomnumbergenerator implementation generate int32 values within specified range.

void generaterandom (int [] data, int mininclusive, int maxexclusive) {     int size = 0;     int length = 0;     byte [] bytes = null;      size = (int) math.ceiling(math.log(math.abs(maxexclusive - mininclusive), 2));     length = data.length * size;     var bytes = new byte [length];      using (randomnumbergenerator generator = randomnumbergenerator.create())     {         generator.getbytes(bytes);     }      // how convert `byte []` `int []` within specified range? } 

one attempt generate random byte array of length (data.length * ((int) math.ceiling(math.log(math.abs(maxexclusive - mininclusive), 2)))) , combine each x number of bytes int. irrespective of specified range, approach of course has disadvantage of huge bias towards larger values since there little chance of multiple significant bytes being zero.

any input appreciated. although i'm using .net here, platform/language doesn't matter. looking conceptual hint.

please note familiar random class in .net interested in figuring out how manually while being able use randomnumbergenerator.

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* = (uint*)b;             for(int j = 0; j < length; j++, i++)             {                 ints[j] = mininclusive + (int)(*i / ratio);             }         }     }      return ints; } 

i've run 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 quite random across numbers between 0 , 300 min.count = 3301 , max.count = 3358.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -