Friday, August 08, 2008

Random number C#.NET

The following code tries to get all the possible numbers in the given range(continuous), by implementing a dictionary that keeps track of the uniqueness and the total count.

Random rnd = new Random();
int max=10, min = 1;
int maxCount = max - min + 1;
Dictionary < int, int > finalDictionary = new Dictionary < int, int > ();

int newValue = rnd.Next(min, max);

if (!finalDictionary.ContainsKey(newValue))
//New key not found in dictionary add it, provide a dummy value
finalDictionary.Add(newValue, 0);

//Stop here, reached maximum
if (finalDictionary.Count == maxCount)

Note: The above program runs infinitely, beware of out of memory!

Apparently .NET framework does not generate the max number in the range. After all MSDN says, the random number generator is not completely random. Albeit, what I do not understand is why doesn't the framework able to get the last number in the range at least once?.

If you want to over come this situation you can go by two ways,
(a) Increase the range by 1. example: make max=11 in the above case or
(b) Keep the maxCount as max-min (instead of max-min+1) and exit the while loop. Finally add the last number to the dictionary.

No comments: