Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.
I was trying to find that if the Random Numbers being generated by the Random function are truly Random or not. So I wrote this small piece of code. When I debug the application it never goes into the else of the IsUnique method. But when I run this application "without debugging" it always print "This is not a random Number". Any ideas !
using System;
using System.Collections; 

namespace RandomNumberTest
{
	
	class Class1
	{
		private static ArrayList randomList = new ArrayList(); 
		private static int notRandom = 0; 
		
		[STAThread]
		static void Main(string[] args)
		{
			
			for(int i=0;i<=10;i++) 
			{
			CreateRandomNumber();
			}
			
		}

		static void CreateRandomNumber() 
		{
			Random d = new Random(); 
			int uniqueKey = d.Next(); 			
			
			IsUnique(uniqueKey); 
		}

		static void IsUnique(int uniqueKey) 
		{
			if( ! randomList.Contains((int) uniqueKey))
			{
				randomList.Add(uniqueKey); 
				Console.WriteLine(uniqueKey); 
			}
			else 
			{
				notRandom++; 
				Console.WriteLine("This is not a random Password:"+uniqueKey);
				Console.WriteLine("Total NOT RANDOM Numbers: "+notRandom); 
			}
		}
	}
}

This is a small piece of code that generates Random Passwords:
 

string alphabets = "abcdefghijklmnopqrstuvwxyz";
string numbers = "01234567890123456789012345";
StringBuilder password = new StringBuilder();
Random r = new Random();
for(int j=0; j<=20;j++)
{
for(int i=0;i<=5;i++)
{
password.Append(alphabets[r.Next(alphabets.Length)]);
password.Append(numbers[r.Next(numbers.Length)]);
}
Response.Write(password.ToString());
password.Remove(0,password.Length);

}

Posted on Friday, July 15, 2005 1:07 PM | Back to top


Comments on this post: Generating Unique Numbers using Random Method

# re: Generating Unique Numbers using Random Method
Requesting Gravatar...
May be because the Random class is supposed to generate random numbers, not unique ones??!!??!!?

Random doesn't mean its unique.........
Left by Wessam Zeidan on Jul 21, 2005 12:28 PM

# re: Generating Unique Numbers using Random Method
Requesting Gravatar...
Thanks for the reply. I know Random class does not generate Unique numbers.The problem is that when I ran the code above and debug it than it always shows me a Random Number but when the message is printed on the screen it says its not a Random Number.


Left by AzamSharp on Jul 21, 2005 12:49 PM

# re: Generating Unique Numbers using Random Method
Requesting Gravatar...
The Random class uses the current time as seed if no parameter is passed to it during construction. You create a new instance of Random each time you generate a new number. When the machine is fast enough, the timestamp returned is the same and hence the number generated are the same.
Left by bc on Oct 01, 2005 3:24 AM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net