Random Numbers are the same!

C

cvnweb

I am trying to generate 2 random numbers that are diffrent, in order to
add them to existing numbers to generate numbers that start out the
same, but are randomly added and subtracted so that they can go down
similar paths, but not be the same. I will implement code later to make
sure i they go more than 10 apart from each other that they are moved
closer together, but this is what I have so far, and when the program
is run, the two random numbers (RA, RB) end up being the same,
resulting in these 2 numbers always being Identicle, how can I prevent
this?

private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
int X=0;
int Y=0;
private void button1_Click(object sender, System.EventArgs e)
{
int RA=RandomNumber(-3,4);
int RB=RandomNumber(-2,5)-1;
X=X+RA;
Y=Y+RB;
if (X<=0 && Y<=0)
{
X=0;
Y=0;
}
else if (Y<=0)
{
Y=0;
}
else if (X<=0)
{
X=0;
}
lblA.Text=X.ToString();
lblB.Text=Y.ToString();
}
 
P

Peter Rilling

You need to "seed" the generator.

new Random(unchecked((int)DateTime.Now.Ticks));
 
C

cvncpu

hmmm, since both numbers are generated at exactly the same time, I
think I need to find another way of generating a new seed, since using
the code snippit you provided doesn't seem to eliviate the situation.
 
F

Fred Mellender

You need to create a Random only once, and then call the same instance
repeatedly to get different random numbers. In some class, (e.g. Foo)
declare
public static Random myRandom = new Random();

then in your private int RandomNumber(int min, int max), omit the
declaration of random, and have:
return Foo.myRandom.Next(min, max);
 
P

Peter Rilling

How about maintaining a global instance of the Random class, seeding it
once, and then you should get random numbers each time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top