473,395 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Cannot randomize from a class

Ant
Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.

When I do it in a controls event, such as button_ click, the numbers are
random as expected, but when I call the random function as a method of a
class, all the numbers are the same for each call to the class.
For example:
(Button click calls the myRandomObject.ReturnValue method)

button click produces 5,5,5
next button click produces 7,7,7
third button click produces 2,2,2

This is basically what is being called when the myRandomObject.ReturnValue
method is called:

Random r = new Random();
string op = r.Next(48,58).ToString();

Why does this work in a button click event but not from a class method? I
would think that the Random instance would be destroyed with each call to the
method.

Any ideas?

Thanks for your help on this
Ant.

Jan 10 '06 #1
7 1996
Ant wrote:
Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.


And I suspect you're creating a new instance of Random for each random
number. That uses a seed based on the current time - and if you create
many instances within a sufficiently short space of time, you'll get
the same seed for each instance, and therefore the same random numbers.

You should be repeatedly using a single instance of Random
See http://msmvps.com/blogs/jon.skeet/ar.../02/77520.aspx for
an easy solution - basically you can use the StaticRandom class in my
Miscellaneous Utility library at
http://www.pobox.com/~skeet/csharp/miscutil to make your life easier.

Jon

Jan 10 '06 #2
> Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.

When I do it in a controls event, such as button_ click, the numbers are
random as expected, but when I call the random function as a method of a
class, all the numbers are the same for each call to the class.
For example:
(Button click calls the myRandomObject.ReturnValue method)

button click produces 5,5,5
next button click produces 7,7,7
third button click produces 2,2,2

This is basically what is being called when the myRandomObject.ReturnValue
method is called:

Random r = new Random();
string op = r.Next(48,58).ToString();

Why does this work in a button click event but not from a class method? I
would think that the Random instance would be destroyed with each call to the
method.

Any ideas?

Thanks for your help on this
Ant.


When you use the constructor without arguments, the seed is used from
the system clock. This means that if you use this repeatedly (in a
loop), the various instances start with the SAME seed value, so
generate the SAME sequence.

So you need to use just a single Random instance to generate a list of
random numbers. One way would be to use a static instance:
(untested code)

class MyRandomObject
{
private static Random rnd = new Random();

public static string NextChar()
{
string op = rnd.Next(48,58).ToString();
return op;
}
}

Hans Kesting
Jan 10 '06 #3
Hi Ant,

you have to take into account that creating two Random objects with
identical seeds will generate the same series of numbers. In your case, you
didn't specify a seed for the Random class constructor, so the System uses
Environment.TickCount (ms elapsed since system start) as default seed. If you
construct x new Random objects in the same millisecond using the default
constructor, your x random objects will have the same seed, and thus generate
the same serie of "random" values.

In your case, you didn't click the button fast enough to see this behavior :-)

Consider the following to demo apps, the first one will have a lot of
similar values in the console output, the second one will have more random
results:

public class MyTestApp
{
public static void Main()
{
for (System.Int32 i=0;i<100;i++)
{
System.Console.WriteLine(new System.Random().Next(45,58));
}
}
}

public class MyTestApp
{
public static void Main()
{
System.Random r = new System.Random();
for (System.Int32 i=0;i<1000;i++)
{
System.Console.WriteLine(r.Next(45,58));
}
}
}

to summarize: either construct one random object and reuse, or make sure you
have a different seed when creating the next random object. (I favor the
first solution)

HTH,
Baileys

"Ant" wrote:
Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.

When I do it in a controls event, such as button_ click, the numbers are
random as expected, but when I call the random function as a method of a
class, all the numbers are the same for each call to the class.
For example:
(Button click calls the myRandomObject.ReturnValue method)

button click produces 5,5,5
next button click produces 7,7,7
third button click produces 2,2,2

This is basically what is being called when the myRandomObject.ReturnValue
method is called:

Random r = new Random();
string op = r.Next(48,58).ToString();

Why does this work in a button click event but not from a class method? I
would think that the Random instance would be destroyed with each call to the
method.

Any ideas?

Thanks for your help on this
Ant.

Jan 10 '06 #4
Actually the docs for Environment.TickCount specify that its resolution
cannot be < 500ms, not 1ms as i mentioned...

"Baileys" wrote:
Hi Ant,

you have to take into account that creating two Random objects with
identical seeds will generate the same series of numbers. In your case, you
didn't specify a seed for the Random class constructor, so the System uses
Environment.TickCount (ms elapsed since system start) as default seed. If you
construct x new Random objects in the same millisecond using the default
constructor, your x random objects will have the same seed, and thus generate
the same serie of "random" values.

In your case, you didn't click the button fast enough to see this behavior :-)

Consider the following to demo apps, the first one will have a lot of
similar values in the console output, the second one will have more random
results:

public class MyTestApp
{
public static void Main()
{
for (System.Int32 i=0;i<100;i++)
{
System.Console.WriteLine(new System.Random().Next(45,58));
}
}
}

public class MyTestApp
{
public static void Main()
{
System.Random r = new System.Random();
for (System.Int32 i=0;i<1000;i++)
{
System.Console.WriteLine(r.Next(45,58));
}
}
}

to summarize: either construct one random object and reuse, or make sure you
have a different seed when creating the next random object. (I favor the
first solution)

HTH,
Baileys

"Ant" wrote:
Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.

When I do it in a controls event, such as button_ click, the numbers are
random as expected, but when I call the random function as a method of a
class, all the numbers are the same for each call to the class.
For example:
(Button click calls the myRandomObject.ReturnValue method)

button click produces 5,5,5
next button click produces 7,7,7
third button click produces 2,2,2

This is basically what is being called when the myRandomObject.ReturnValue
method is called:

Random r = new Random();
string op = r.Next(48,58).ToString();

Why does this work in a button click event but not from a class method? I
would think that the Random instance would be destroyed with each call to the
method.

Any ideas?

Thanks for your help on this
Ant.

Jan 10 '06 #5
I don't know about your exact scenario (not enough code to reproduce), but a
better option is to cache the Random() instance between calls (presumably in
a field if you are using a wrapper class). This means that subsequent calls
will return pseudo-random results (updating the object seed each call to
Next()), where-as "new Random()" simply initialises a new object using the
time to create a seed.

Personally, unless I need reproducable results (with same starting seed), I
tend to use a static wrapper, so that all my code can use
MyWrapper.Next(48,58) to share the same random object (obviously you may
need to make this thread-safe).

Marc

"Ant" <An*@discussions.microsoft.com> wrote in message
news:5C**********************************@microsof t.com...
Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.

When I do it in a controls event, such as button_ click, the numbers are
random as expected, but when I call the random function as a method of a
class, all the numbers are the same for each call to the class.
For example:
(Button click calls the myRandomObject.ReturnValue method)

button click produces 5,5,5
next button click produces 7,7,7
third button click produces 2,2,2

This is basically what is being called when the myRandomObject.ReturnValue
method is called:

Random r = new Random();
string op = r.Next(48,58).ToString();

Why does this work in a button click event but not from a class method? I
would think that the Random instance would be destroyed with each call to
the
method.

Any ideas?

Thanks for your help on this
Ant.

Jan 10 '06 #6
Hans Kesting wrote:
When you use the constructor without arguments, the seed is used from
the system clock. This means that if you use this repeatedly (in a
loop), the various instances start with the SAME seed value, so
generate the SAME sequence.

So you need to use just a single Random instance to generate a list of
random numbers. One way would be to use a static instance:
(untested code)

class MyRandomObject
{
private static Random rnd = new Random();

public static string NextChar()
{
string op = rnd.Next(48,58).ToString();
return op;
}
}


Note, however, than Random is not thread-safe. It sounds like it may
not be a problem in the OP's case, but you need to make sure you don't
use the same instance across multiple threads.

Jon

Jan 10 '06 #7
Ant
Thank you all, you were all right on target. I was using a new instance of
the Random class with each call. Hence the seed was the same. I just worked
around it by creating the string within the method being called using a
single instance of the Random class.

Thanks all.

"Marc Gravell" wrote:
I don't know about your exact scenario (not enough code to reproduce), but a
better option is to cache the Random() instance between calls (presumably in
a field if you are using a wrapper class). This means that subsequent calls
will return pseudo-random results (updating the object seed each call to
Next()), where-as "new Random()" simply initialises a new object using the
time to create a seed.

Personally, unless I need reproducable results (with same starting seed), I
tend to use a static wrapper, so that all my code can use
MyWrapper.Next(48,58) to share the same random object (obviously you may
need to make this thread-safe).

Marc

"Ant" <An*@discussions.microsoft.com> wrote in message
news:5C**********************************@microsof t.com...
Hi, I'm using the Random class to return 5 random numbers which then are
added to a string.

When I do it in a controls event, such as button_ click, the numbers are
random as expected, but when I call the random function as a method of a
class, all the numbers are the same for each call to the class.
For example:
(Button click calls the myRandomObject.ReturnValue method)

button click produces 5,5,5
next button click produces 7,7,7
third button click produces 2,2,2

This is basically what is being called when the myRandomObject.ReturnValue
method is called:

Random r = new Random();
string op = r.Next(48,58).ToString();

Why does this work in a button click event but not from a class method? I
would think that the Random instance would be destroyed with each call to
the
method.

Any ideas?

Thanks for your help on this
Ant.


Jan 11 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Fieldmedic | last post by:
I'm trying to determine the best way to randomize a set of array items. I'm thinking that I could use an arraylist and have it use the lower and upper bounds as the limits. Any suggestions? ...
3
by: Gaffer | last post by:
Hello Is there a way in which I can make certain parts of Html on my website random so that each viewer will see different material if they refresh the page or come back onto the website later?...
1
by: Ellen Manning | last post by:
I've got an A2K database with a report that generates any number of random medical record numbers. The user inputs how many numbers they want and report uses the Randomizer function found on "The...
3
by: Starbuck | last post by:
Hi all Is there a function in c# like the VB randomize command Thanks in advance --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com).
4
by: Mr. x | last post by:
Hello, randomize is a function in vbscript. What is the function for vb ? (I have tried to use that command in the script in web-service of .net, which used VB and not VBScript). Thanks :)
2
by: Rich | last post by:
Here is what I am trying for randomizing 2 numbers in the same subroutine so that they are not equal to each other: Dim j As Integer, k As Integer j = New System.Random().Next(0, 10) k = New...
1
by: Badass Scotsman | last post by:
Hello, This code is supposed to generate a random string each run, however I have had it live on a few sites, and it seems to create repeat strings all over the place. ...
1
by: VBSTUDENT | last post by:
I am just wondering if there is a way to randomize the aritmetic operators in code, I know how to randomize numbers but I am not sure if it is possible to randomize operators. Any help would be...
5
by: gggram2000 | last post by:
Hi, I'ved spent two full days trying to find a solution, I can randomize numbers between two ranges and it works fine, But my problem is when i want to randomize five numbers that I got. eg. I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.