Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange behaviour with randomising 1

Status
Not open for further replies.

tcstom

Programmer
Aug 22, 2003
235
GB
I hope someone can get their head round this because it's driving me nuts! I have the following static method in a class called Pie which returns a random hex value:

Code:
public static string RandomHex()
{
	string strValidChars = "0123456789ABCDEF";
	string strRandomHex = String.Empty;
	Random objRandom = new Random();
	for (int i = 0; i < 6; i++)
	{
		int intRandom = objRandom.Next(0, strValidChars.Length);
		strRandomHex += strValidChars[intRandom];
	}
	return strRandomHex;
}

By itself this works, but if I repeatedly call it I find it keeps returning the same 'random' value (although this value is different on each page load). In other words, if I use the code...

Code:
for (int i = 0; i < 10; i++)
{
	Response.Write(Pie.RandomHex() + "<br />");
}

...I'm getting a response of something like this:

Code:
6F6AE0
6F6AE0
6F6AE0
6F6AE0
6F6AE0
6F6AE0
6F6AE0
6F6AE0
6F6AE0
6F6AE0

Then I refresh the page and get something like this:

Code:
2ED772
2ED772
2ED772
2ED772
2ED772
2ED772
2ED772
2ED772
2ED772
2ED772

Now, here's the really odd thing, if I stick a breakpoint in the method and debug it, the output is correct i.e. something like this:

Code:
168903
CCAFCC
6B3751
13C785
663CD4
3F6390
377D7A
8390C1
63F83A
74B11D

But as soon as I remove that breakpoint again it resorts back to repeating the same value. Can anyone replicate this behaviour? And if so, what's going on???
 
Yes, that is what I would expect as the Random value will be created with the same seed - it has an overloaded method that allows you to set the seed if you look at the help file or intellisense. Try passing something into the seed parameter when you call it (System.DateTime.Now.Millisecond for example).

As a side note, I notice that although you have asked nearly 40 questions on the forums here, you have only marked 2 of the answers as valuable. If you are not getting the answers that you need read FAQ222-2244 to see how to ask better questions. If you are getting the answers you need see FAQ222-2244 to see how to acknowledge the answers given.

Paragraph 16 of the FAQ explains about this being a two-way forum, to give guidance on answering other peoples questions, as I also notice that you haven't yet made any posts in other peoples threads.


-------------------------------------------------------

Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]
[URL unfurl="true"]http://mdssolutions.co.uk[/url] - Delivering professional ASP.NET solutions
[URL unfurl="true"]http://weblogs.asp.net/marksmith[/url]
 
To address my question first, thank you for the information. I didn't realise the Random class worked like that. I've now changed the method to this...

Code:
public static string RandomHex()
{
	string strValidChars = "0123456789ABCDEF";
	string strRandomHex = String.Empty;
	for (int i = 0; i < 6; i++)
	{
		Random objRandom = new Random(DateTime.Now.Millisecond);
		int intRandom = objRandom.Next(0, strValidChars.Length);
		strRandomHex += strValidChars[intRandom];
	}
	return strRandomHex;
}

...but I'm still largely getting the same behaviour, presumably because the series of random numbers are getting generated within the same millisecond (if I run a similar loop to my code posted above but hundreds of times then the random numbers appear repeated in blocks, presumably spanning a millisecond each). It seems to me that I need a way of providing a random number as a seed which rather defeats the object, so do you have any alternative methods of achieving my aim?

To address your other points, I admit that I often fail to mark valuable answers as such. I hadn't realised the importance but I will go back through my previous threads and update them. But I have responded to other posts in the past, admittendly not recently. I don't know why your stats say otherwise. I do often look through posts to see if I can help but the truth is that experts like you often respond with valuable answers in a matter of minutes, so it's not easy at all to beat you to the answer. I will continue to try to do so though.
 
If you are going to be calling the function in very quick succession, you will need a seed that is unique. Something like System.DateTime.Now.Ticks may be more unique than Millisecond.


-------------------------------------------------------

Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]
[URL unfurl="true"]http://mdssolutions.co.uk[/url] - Delivering professional ASP.NET solutions
[URL unfurl="true"]http://weblogs.asp.net/marksmith[/url]
 
you don't need to instantiate random with each function call. instead make random an private field that is initiated in the constructor. then remove the static keyword from the function.
Code:
public class RandomHex()
{
  private static readonly char[] hexValues = "0123456789ABCDEF".ToCharArray();

  private Random randomizer = new Random(DateTime.Now.Millisecond);

  public string GetNext()
  {
    StringBuilder toReturn = new StringBuilder();
    for (int i = 0; i < 6; i++)
    {
        toReturn.Append(hexValues[randomizer.Next(0, 15)]);
    }
    return toReturn.ToString;
  }
}
Code:
RandomHex hexGenerator = new RandomHex();
string hex1 = hexGenerator.GetNext();
string hex2 = hexGenerator.GetNext();
string hex3 = hexGenerator.GetNext();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
I had the same problem. I was getting the same value because of the seed, which is based on time. What I did was to create a property which then called the Random() function.
 
As a side note, I notice that although you have asked nearly 40 questions on the forums here, you have only marked 2 of the answers as valuable. If you are not getting the answers that you need read FAQ222-2244: How to get the best answers to see how to ask better questions. If you are getting the answers you need see FAQ222-2244: How to get the best answers to see how to acknowledge the answers given.

Perhaps one could elucidate an optimal question/star threshold that posters should adhere to. Do people really have that much time on their hands to keep track of these sort of meaningless stats?
 
Perhaps one could elucidate an optimal question/star threshold that posters should adhere to. Do people really have that much time on their hands to keep track of these sort of meaningless stats?
There isn't an optimal percentage, but it does provide an easy way to show if the poster is getting the help they desire. It's not hard to click on a persons name to find those stats so I'd hardly call it time consuming for you to find that information out...


-------------------------------------------------------

Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]
[URL unfurl="true"]http://mdssolutions.co.uk[/url] - Delivering professional ASP.NET solutions
[URL unfurl="true"]http://weblogs.asp.net/marksmith[/url]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top