473,581 Members | 6,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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).T oString();

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 2012
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).T oString();

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.Tic kCount (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.Nex t(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).T oString();

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.Tic kCount 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.Tic kCount (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.Nex t(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).T oString();

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*@discussion s.microsoft.com > wrote in message
news:5C******** *************** ***********@mic rosoft.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).T oString();

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*@discussion s.microsoft.com > wrote in message
news:5C******** *************** ***********@mic rosoft.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).T oString();

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
14992
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? Cheers, Steve
3
14622
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? I am currently using the "<!--#include virtual="cgi-bin/menu1.txt" -->" command to display my menus on every page of my site, so that the same...
1
3419
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 Access Web" site to generate these numbers. Out of 38000 records, there are 900 unique medical record numbers. I run the randomizer function on a...
3
4051
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
6693
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
2473
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 System.Random().Next(0, 10) But j and k are always equal to each other. So I through in Randomize( ) but that did not help. Is it possible to...
1
3759
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. ------------------------------------------------------------- <% FUNCTION GetRandomCode(randomcode,codelength,numberofcombinations) codecharacters = 35
1
2148
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 appreciated Thanks
5
2881
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 randomize 1-100 and I get 50. I randomize 1-900 on another input field and I get 578. I randomize 2-56 and get 31. " " and get 43. " " and get...
0
7788
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8137
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8299
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7887
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8162
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6543
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5667
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3811
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1397
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.