I'm working on Pong in C# w/ XNA.
I want to use a random number (within a range) to determine things such as whether or not the ball rebounds straight, or at an angle, and how fast the ball moves when it hits a paddle.
I want to know how to implement it.
Use the Random class. For example:
Random r = new Random();
int nextValue = r.Next(0, 100); // Returns a random number from 0-99
Unless you need cryptographically secure numbers, Random should be fine for you... but there are two gotchas to be aware of:
You shouldn't create a new instance every time you need one. If you create an instance without specifying a seed, it will use the current time as the seed - which means if you create several instances in quick succession, many of them will produce the same sequence of numbers. Typically you create a long-lasting instance of Random and reuse it.
It's not thread-safe. If you need to generate random numbers from multiple threads, you should think about having one instance per thread. Read this blog post for more information - but make sure you read the comments as well, as they have very useful information.
Random rnd = new Random();
rnd.Next(minValue, maxValue);
i.e.
rnd.Next(1,10);
Use the Random object's Next method that takes a min and max and returns a value in that range:
var random = new Random();
int randomNum = random.Next(min, max);
While you can use the Random class like all the other are suggesting, the Random class only uses psuedo-random number generation. The RandomNumberGenerator, which can be found in the System.Security.Cryptography namespace, creates actual random numbers.
How To Use:
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] rand = new byte[25]; //Set the length of this array to
// the number of random numbers you want
rng.GetBytes(rand);
More Info: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=VS.80).aspx
Here is my random generator
private static Random rnd = new Random(Environment.TickCount);
private int RandomNum(int Lower, int Upper)
{
return rnd.Next(Lower, Upper);//MyRandomNumber;
}
Related
I am trying to access random elements from an array, but the Random generator that I am using keeps on giving me numbers in order like so:
The numbers will always come out sequenced, never completely random (ie. the next number is always greater until the max is reached, then starts from low numbers again). This can be incremental or decremental as well.
I am using a seeded Random object and Random.Next(-100, 100).
This is not the same as the behaviour demonstrated on the MSDN Random.Next page
All I can think of is that the version of .Net packaged with Unity does not have the most recent Random? Any solutions to this confusion?
//Example
//Seed and ods set before the Awake method is called
public int seed;
public GameObject[] pathPartOds;
Random random;
GameObject[] path;
void Awake ()
{
random = new Random (seed);
}
void CreatePath (int length)
{
path = new GameObject[length];
for (int i = 0; i < length; i++)
path[i] = pathPartOds[random.Next (0, pathPartOds.length)];
}
Have used multiple seeds and they all give the same result, and I have been creating seeds using a random int
You need to create an instance of Random exactly once and pass that as a parameter into your function that draws a random number.
Else you'll ruin the generator's statistical properties due to it being seeded in a systematic (i.e. non-random) way. That explains the piecewise monotonicity of your output.
In my .NET game my rand function that are determining how much damage each out of the players five characters should take, however the 1st one always seems to be at the bottom of the scale and the last one at the top. So in my Character[0] the damage is rarely more than 1 more than the minimum rand value, and for each Character on higher index the damage taken is only randomized from higher up the scale.
public int GetDamage(int low, int high)
{
Random r = new Random();
int rand = r.Next(low, high);
return rand;
}
This is the randomizer I use. Then I update the health left like this:
int Damage = GetDamage(3, 10);
Characters[Target].Health = Characters[Target].Health - Damage;
In this example dmg is divided like this:
Number 1: 3-4
Number 2: 4-6
Number 3: 5-7
Number 4: 7-8
Number 5: 8-9
You have to reuse the same random instance otherwise you won't get really random values since it is created with the current time as seed. If you call GetDamage very fast(e.g. in a loop) you will get always the same values.
So either use a field/property in the class of GetDamage or pass the random instance to the method.
private Random _rnd = new Random();
public int GetDamage(int low, int high)
{
int rand = _rnd.Next(low, high);
return rand;
}
MSDN
The random number generation starts from a seed value. If the same
seed is used repeatedly, the same series of numbers is generated. One
way to produce different sequences is to make the seed value
time-dependent, thereby producing a different series with each new
instance of Random. By default, the parameterless constructor of the
Random class uses the system clock to generate its seed value, while
its parameterized constructor can take an Int32 value based on the
number of ticks in the current time. However, because the clock has
finite resolution, using the parameterless constructor to create
different Random objects in close succession creates random number
generators that produce identical sequences of random numbers. This
problem can be avoided by creating a single Random object rather than
multiple ones.
You need to make your Random instance static, this seeds it once and thereafter you will get a more random looking number.
static Random r = new Random();
public int GetDamage(int low, int high)
{
int rand = r.Next(low, high);
return rand;
}
You need to seed the random number generator.
See: How do I seed a random class to avoid getting duplicate random values
Literally hundreds of this question on here, have a look around.
if I have this:
(I already declared the variables)
random1 = new Random();
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
When I have that, it'll generate a different number for every time I call console.writeline, so this would generate ex. 10, 55 and if you do it again 20,60 so basically random numbers each time, good.
But when I add this:
random2 = new Random();
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random2.Next(1, 100));
Console.WriteLine(random2.Next(1, 100));
Random1 will generate the same numbers as random! So it will be ex. 5,54,5,54 and if i do it again 70,34,70,34. But it's random2 is a new object so why is it generating the same numbers as random1??
Another example:
If I have class like this
class RandomNumber
{
Random random = new Random();
public int getrandomnumber { get { return random.Next(1, 5); } }
}
After doing this
randomnumberobject = new RandomNumber();
randomnumberobject2 = new RandomNumber();
Console.WriteLine(randomnumberobject.getrandomnumber);
Console.WriteLine(randomnumberobject2.getrandomnumber);
They'll generate a random number, but both of them will generate the exact same random number. So first time i'd get this 5,5 second time this 3,3 and so on.
But if I change the class to this
class RandomNumber
{
Random random;
public int getrandomnumber { get { return random.Next(1, 5); } }
public RandomNumber(Random random) { this.random = random; }
}
And do this instead
random = new Random();
randomnumberobject = new RandomNumber(random);
randomnumberobject2 = new RandomNumber(random);
Console.WriteLine(randomnumberobject.getrandomnumber);
Console.WriteLine(randomnumberobject2.getrandomnumber);
Suddenly, they both generate different random numbers! So why does this happen? What's the reason? Keep in mind, I'm still kind of a beginner.
What you see is "by design" - i.e. it happens because of how the class is implemented... the algorithm it uses needs a "seed" (kind of a starting state) which in this case is based on the clock... as documented on MSDN:
The random number generation starts from a seed value. If the same
seed is used repeatedly, the same series of numbers is generated. One
way to produce different sequences is to make the seed value
time-dependent, thereby producing a different series with each new
instance of Random. By default, the parameterless constructor of the
Random class uses the system clock to generate its seed value, while
its parameterized constructor can take an Int32 value based on the
number of ticks in the current time. However, because the clock has
finite resolution, using the parameterless constructor to create
different Random objects in close succession creates random number
generators that produce identical sequences of random numbers. The
following example illustrates that two Random objects that are
instantiated in close succession generate an identical series of
random numbers.
This means basically that if two Random objects are created at nearly the same time using the parameterless constructor they will produce the same sequence of random numbers since they have been initialized with the same "starting state" based on the clock.
Random number generation works based on a seed value in most of the programming languages. This seed is usually taken from a current time value. So if you declare the two Random objects close to each other, most likely they will obtain the same seed from the CLR. That's why they will generate the same numbers.
When you use the same instance, the first two numbers will already come from the random sequence, so the next two won't be the same.
Use the explicit seed in such situations (the constructor of Random which is overloaded with an int value).
Because you are reseeding each time in the last example, if you don't reseed random object will pull from the same pool of random numbers each time.
var random1 = new Random(DateTime.Now.Millisecond);
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
Console.WriteLine(random1.Next(1, 100));
var random2 = new Random(DateTime.Now.Millisecond);
Console.WriteLine(random2.Next(1, 100));
Console.WriteLine(random2.Next(1, 100));
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 9 years ago.
having an issue generating random numbers in a loop. Can get around it by using Thread.Sleep but after a more elegant solution.
for ...
Random r = new Random();
string += r.Next(4);
Will end up with 11111... 222... etc.
Suggestions?
Move the declaration of the random number generator out of the loop.
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, ...
Source
By having the declaration in the loop you are effectively calling the constructor with the same value over and over again - hence you are getting the same numbers out.
So your code should become:
Random r = new Random();
for ...
string += r.Next(4);
Random r = new Random();
for ...
string += r.Next(4);
new Random() will initialize the (pseudo-)random number generator with a seed based on the current date and time. Thus, two instances of Random created at the same date and time will yield the same sequence of numbers.
You created a new random number generator in each iteration and then took the first value of that sequence. Since the random number generators were the same, the first value of their sequences was the same. My solution will create one random number generator and then return the first, the second, etc... value of the sequence (which will be different).
I found a page in Chinese that said the same with the time: http://godleon.blogspot.hk/2007/12/c.html, it said if you type like this:
Random random = new Random(Guid.NewGuid().GetHashCode());
you MAY get a random number even in a loop! It solved my question as well!
You should be using the same Random instance throughout instead of creating a new one each time.
As you have it:
for ...
Random r = new Random();
string += r.Next(4);
the seed value is the same for each (it defaults to the current timestamp) so the value returned is the same.
By reusing a single Random instance like so:
Random r = new Random()
for ...
string += r.Next(4);
Each time you call r.Next(4) the values are updated (basically a different seed for each call).
Move the Random r = new Random(); outside the loop and just call next inside the loop.
For a part of a program i need the following 2 methods.
The first method listed will generated a random number.
where the 2nd method will "call" this method to fill the array.
The array has a max. number of elements defefined on 100 (and all the random generated numbers should be between 1-100).
The problem is i never get random numbers generated. (either i get 100 x the same value, 3 random numbers divided over the 100 max. elements of the array, or the same value 100 times all over again).
The problem should be in the first method, but i cannot seem to figure out the problem.
Been staring at this for quite some time now...
The problem should be with the return, cause it DOES create random generated numbers. But how do i return the generated value every time? (the int method has to be called with the 3 parameters).
private int ValidNumber(int[] T, int X, int Range)
{
for (byte I = 0; I < T.Lenght; I++)
{
Random RndInt = new Random();
X = RndInt.Next(1, Range+1);
}
return X;
}/*ValidNumber*/
public void FillArray(int[] T, int Range)
{
for (byte I = 0; I < T.Length; I++)
{
T[I] = ValidNumber(T, I, Range);
}
}/*FillArray*/
Console code:
public void ExecuteProgram()
{
ClsBereken Ber = new ClsBereken();
//const byte Range = 100;
const int Max = 100;
int[] T = new int[Max];
Ber.FillArray(T, Max);
DisplayArray(T);
}/*ExecuteProgram*/
private void DisplayArray(int[] T)
{
for (byte i = 0; i < T.Length; i++)
{
Console.Write("{0,4} ", T[i]);
}
Console.WriteLine();
}/*DisplayArray*/
Any help alot appreciated.
Kind Regards.
Re-use the Random instance. NOTE I've edited this to show passing the Random instance down, but I'm really not sure what ValidNumber is trying to do - it looks like it is juts burning up CPU cycles? I would suggest you can remove ValidNumber completely (and just use the next value from the Random in FillArray), but presumably you are trying to do something here - I'm just not sure what!
private int ValidNumber(int[] T, int X, int Range, Random random)
{
for (byte I = 0; I < T.Lenght; I++)
{
X = random.Next(1, Range+1);
}
return X;
}/*ValidNumber*/
public void FillArray(int[] T, int Range)
{
Random random = new Random();
for (byte I = 0; I < T.Length; I++)
{
T[I] = ValidNumber(T, I, Range, random);
}
}/*FillArray*/
When you create a Random, it is "seeded" using the system clock, but this is rounded heavily. If you create lots of Random in a tight loop, they all get the same "seed", so they all create the same next number.
If necessary you could move the Random further out (if you have other loops), or make it static (but if you do that you need to worry about synchronization too).
The problem is that you are reinitializing rndint over and over.
take the line:
Random RndInt = new Random();
and move it in front of the loop and see if that fixes it.
When you initialize a random object, it is assigned a seed (probably based on the time), and that seed is used to generate a series of seemingly random values. However, if you plug in the same seed to two random objects, you will get the same series of random numbers.
So, what is happening in your code is you are initializing a new random object with a seed, and then asking for the first random number in its series. Then, you are initializing another random object (even though it is assigned to the same name, it is a new object) and it is getting the same seed, and you are again asking for the first random number in the series. So naturally, you are getting the same random number over and over.
You are continuously creating an new Random object. I'm afraid this is seeded (randomized) by the timestamp of creation. Since this is really fast and happens multiple times, the seed is the same, and so is the result of the call RndInt.Next(1, Range+1);.
By the way, even though not incorrect, it's not a common practice in c#.net to start with a capital letter on names of local variables and parameters.
Any random number generation algorithm* is not truly random; it is simply a deterministic algorithm that has been specifically designed to output numbers that resemble randomness. (See Pseudorandom number generator.) Since the algorithm is deterministic, its output is completely dependent upon a starting "seed" value.
The Random class in .NET has two constructors: one which takes an integer seed, and another which takes no parameters. This one bases its seed off the current time.
From this information perhaps you can guess why creating a new Random instance for every value in your array results in the entire array being filled with the same number: every time you construct a Random object within a very small time frame, it will have the same seed value, which means it will generate identical output to another Random object constructed within the same time frame.
As Marc Gravell has already indicated, you should be using only a single Random instance to generate a sequence of random numbers.
*Well, almost any. I believe there are hardware implementations of random number generators that factor in random noise (taken from the surrounding environment) and may therefore be considered "truly" random. Whether you believe these are actually random
depends on your personal definition of "random" and whether or not you believe that we live in a deterministic universe.
You can pass Random() a seed but if you send it the same seed number you will get the same results. The way you are using it
Random rnd = new Random();
Is using an auto-generated seed based on time. But you may not get seemingly random results if you don't at least sleep for a second. (Source http://msdn.microsoft.com/en-us/library/system.random(VS.71).aspx)
As everyone has mentioned here already your biggest issue is the fact you keep recreating the random object each iteration.