This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 1 year ago.
how can i generate different number,it is generating the same number
Random rand = new Random(100000);
rand.Next();
Just remove the seed number in the constructor. This seed is essentially a number from which the random number list is generated. If you specify a constant number, your random number list will always be the same.
Random rand = new Random();
rand.Next();
Your specifying the same seed try this.
Random rand = new Random();
rand.Next();
This will use the default seed which is the time.
"Initializes a new instance of the Random class, using a time-dependent default seed value."
As per MSDN : http://msdn.microsoft.com/en-us/library/system.random.aspx
Re your comment above, how to generate a "random" number in a set range.
// Generate and display 5 random integers from 50 to 100.
Console.WriteLine("Five random integers between 50 and 100:");
Console.Write("{0,8:N0}", rand.Next(50, 101));
(Taken from MSDN link above) You can now generate whatever range you want.
Not sure exactly what you are after!
Random rand = new Random(Environment.TickCount);
rand.Next();
Random rand=new Random(DateTime.Now.Millisecond);
rand.Next();
This always works for me.
Random rand = new Random();
rand.Next(0,1000); // minimum = 0, maximum = 999
Related
how can I get two strings from two arrays randomly. I have something, but It doesn't pick randomly.
string[] firstNames = { "John", "Michael", "Victor", "Mark", "Alex", "Steven", "Zack", "Howard", "Xzavier", "Brendan", "Dustin", "Carl" };
string[] lastNames = { "Adams", "McGregor", "Piasta", "Semmel", "Laris", "Sever", "Bourque", "Percy", "Shanabarger", "Bobak", "Adair" };
string[] shuffled = firstNames.OrderBy(n => Guid.NewGuid()).ToArray();
string[] shuffled2 = firstNames.OrderBy(n => Guid.NewGuid()).ToArray();
Random firstn = new Random();
Random lastn = new Random();
int index = firstn.Next(firstNames.Length);
int index2 = lastn.Next(lastNames.Length);
Console.WriteLine($"The random name is {firstNames[index]}" + $" {lastNames[index2]}");
I am trying to make a random full name generator. I have tried this code multiple times and the results were: John Adams, Victor Piasta, and so on! And as you can see they are not random.
Looks pretty random to me..
With 150 iterations you still get a performance of roughly 90 of 132 possible combinations.
Testing code:
HashSet<string> names = new HashSet<string>(150);
Random rndm = new Random();
for (int i = 0; i < 150; i++)
{
names.Add($"{firstNames[rndm.Next(firstNames.Length)]} " +
$"{lastNames[rndm.Next(lastNames.Length)]}");
}
Console.WriteLine($"{names.Count} / {firstNames.Length * lastNames.Length}");
Console.ReadKey();
Don't forget that true random is not possible to simulate... so you will always have some kind of repetitive distribution with higher numbers.
Random works slightly different in .NET-Framework to .NET-Core
In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator.
From: https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1#Instantiate
In the .NET-Framework only, on most Windows systems, Random objects created within 15 milliseconds of one another are likely to have identical seed values.
Use a single Random-instance on .NET-Framework to avoid this behaviour.
Just change to below so that you are using the same Random instance for both
int index2 = firstn.Next(lastNames.Length);
Random does not actually generate random numbers, but pseudo-random numbers. That means, you need a starting value, the so-called seed. From that value the first number is calculated. From that, one could calculate another number, and so on. These numbers look like random, but actually they are determined by the seed. If you have the same seed, you always get the same sequence of numbers.
Your Random class has actually a constructor where you can deliver a seed. You can try it out here: https://dotnetfiddle.net/0bHDNg For the same seed, you will always get the same sequence of numbers.
If you use the constructor without a parameter, the current time is taken as the seed. This has the big advantage, that you always get a different sequence of numbers when you restart the program. But in your example, you have a problem: If the time between creating the two instances of Random has not changed, because the computer is so fast, they will have both the same seed and thus both the same sequence of numbers. That's why index and index2 both have the same value. Just use the same instance of Random for generating both indices, and they don't have necessarily the same value:
Random random = new Random();
int index = random .Next(firstNames.Length);
int index2 = random .Next(lastNames.Length);
Console.WriteLine($"The random name is {firstNames[index]}" + $" {lastNames[index2]}");
I'm looking for some help with my array. to put it in context im trying to create a console application that randomly generates a 4-digit code for the user to guess.
to do this I need an array of [3] and they need to have random numbers assigned to it.
int[] secretCode = new int[3];
secretCode[0] =
secretCode[1] =
secretCode[2] =
secretCode[3] =
My concern is what would i put here to make them generate random numbers?
thank you for your help in advance.
You can use Linq and the Random class
Random rnd = new Random();
int[] secretCode =
Enumerable.Repeat(0, 4).Select(i => rnd.Next(1000, 10000)).ToArray();
or more traditionally
int SIZE = 4;
Random rnd = new Random();
int[] secretCode = new int[SIZE];
for (int i = 0; i < SIZE; i++)
{
secretCode[i] = rnd.Next(1000, 10000);
}
Note that there is a possibility of creating the same code more than once. The solution assumes you want something in the range 1000..9999 (10000 is an exclusive upper bound) since the code is to be 4 digits. If you would also allow smaller numbers, just adjust the Select portion.
As a side note, do not create a new instance of Random inside the select, as it would likely be reseeded to the same seed, based on the system time, resulting in the same "random" number over and over. Also Random is fast, but not cryptographically strong. If you need cryptographically valid randomness use RNGCryptoServiceProvider in place of Random.
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));
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;
}
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.