Random.Next not working? [duplicate] - c#

This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 5 years ago.
I'm trying to make a random room selector and Random.Next seems to not be working, please help!
List<string> rooms = new List<string>();
rooms.Add(room1);
rooms.Add(room2);
int index = Random.Next(rooms.Count);
System.Console.WriteLine(rooms[index]);
The systems I am using (I think this may be the problem)
Using System
Using System.Collections.Generic
Using.Collections
Using.Collections is greyed out.

your issue is that you want to call the Next method directly on the Random class, unfortunately, there is no static Next method for the Random class.
int index = Random.Next(rooms.Count);
you'll need to make an instance of the Random generator, in order to invoke the Next method.
Example:
Random rand = new Random();
int index = rand.Next(rooms.Count);
System.Console.WriteLine(rooms[index]);
further reading:
How do I generate a random int number in C#?

Related

How can i randomize (NOT SHUFFLE) a string? [duplicate]

This question already has answers here:
How can I pick a random string from an array and display it in a text box?
(2 answers)
Closed 3 years ago.
So how can i randomize a string ? For example
Console.WriteLine(string);
I want it to write with 50/50 chance
String1, string2
You can use the Random type to generate a random number between a min and max value.
string[] strings = new[] {"abc", "def"};
Random random = new Random();
int randomArrayPosition = random.Next(0, strings.Length);
for (int i = 0; i < 10; i++)
{
Console.WriteLine(strings[randomArrayPosition]);
}
The above however isn't cryptographically random, it uses the system clock to provide a seed value, if you were to use this seed value when creating the Random class, the results would always be the same.

C# cannot generate a random string [duplicate]

This question already has answers here:
Random.Next returns always the same values [duplicate]
(4 answers)
Random number generator only generating one random number
(15 answers)
Closed 5 years ago.
I cannot work out why C# is doing this.
Here's my code;
private string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string randomString = "";
for(int i = 0; i < length; i++)
{
randomString += chars.ToCharArray()[new Random().Next(chars.ToCharArray().Length)];
}
return randomString;
}
First result:
"wwwwwwwwwwwwwwwwwwww"
Second result:
"ssssssssssssssssssss"
Third result:
"mmmmmmmmmmmmmmmmmmmm"
When you generate a random number generator using new Random(), its seed will be based on the current time, so it will end up being the same thing for each iteration of the loop, since execution will be fast. Instead, you want a var rng = new Random() outside of the loop, and use rng.Next inside the loop.

Looping through a method call too fast? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
I am calling a method instance called buy. My method randomly generates a string of digits and numbers. My for loop appears to be going to fast for the method to change the string because I get the same string like 2-3 times in a row before getting a new string. when i add a System.Threading.Thread.Sleep(100); I am getting random number like the way it is supposed to be. The problem is that it is way too slow and i feel like there must be a better way. is there a way to get random string each time without invoking the Sleep() method?
for (int i = 0; i < exit; i++)
{
ticket = buy.SetNum();
Console.WriteLine("Wellcome Mr.Nissan. The winning numbers for Lotto max are:");
Console.WriteLine(ticket);
System.Threading.Thread.Sleep(25);
}
Yes, this is a problem with your random number generator - not with the code you posted in the question.
consider the following:
public int GenRandomNum()
{
var r = new Random();
return r.Next()
}
You are generating a new random class based on the same seed if you call it in the same tick, and it will generate the same number. Moving the random initialization out side of the method will fix the problem, like so:
private Random _rand = new Random();
public int GenRandomNum()
{
return _rand .Next()
}
You haven't included the code that actually creates the random number but I suspect you're creating a new instance of the random number generator each time around the loop.
What you need to do instead, is create one instance of the random number generator (outside of the loop) and reuse it for each random number generator .Next() call.
Move the random number generation into into the loop:
var rnd = new Random();
for (int i = 0; i < exit; i++)
{
var ticket = rnd.Next();
Console.WriteLine("Wellcome Mr.Nissan. The winning numbers for Lotto max are:");
Console.WriteLine(ticket);
}
I can't tell you why exactly your posted code wasn't working without seeing the buy.SetNum(); method code.

Math Random Coin Toss [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 9 years ago.
I wrote a function A, and inside this function there is below code piece.
rnd.Next(1,3);
If I run my A function hundred times, and print out the results, results are not realistic for example it is always win or always lose. So the random function is problematic. I need a realistic real random function.
How to achieve that ?
I guess you've done a typical error with Random, you're re-creating it each time i.e:
Random rnd = new Random();
int toss = rnd.Next(1,3);
If you do this, rnd could well start each time from the same seed and that's why the result is badly skewed. The solution can be something like that:
// Let it be thread-safe
private static ThreadLocal<Random> s_Gen = new ThreadLocal<Random>(
() => new Random());
// Thread-safe non-skewed generator
public static Random Generator {
get {
return s_Gen.Value;
}
}
...
int toss = Generator.Next(1,3);
Use this
int i = rnd.Next(int.MaxValue) % 2;
Then have a check whether i = 0 or i = 1.
EDIT Yes, as Dmitry Bychenko mentioned do not instantiate a new Random object each time.

same random values [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Random number generator not working the way I had planned (C#)
Why does it appear that my random number generator isn't random in C#?
I have a problem with random values
int weight = 0;
Random random = new Random();
for (int i = 0; i < entriesCount; i++)
{
weight = random.Next(10);
this.weights[i] = weight;
}
This code is in constructor of my object. I create 3 diffrent objects
Object object1 = new Object(2);
Object object2 = new Object(2);
Object object3 = new Object(2);
For every object I get same random values for example: 4, 5 | 4, 5 | 4, 5
Every time I get same values in same sequence. I don`t get why> Please help
Best regards,
Dawid
The problem is that you're creating a new Random each time. When you create an instance of the Random class, it uses the current time as a seed. If you do this multiple times very quickly, you get the same seed value, so the different Random instances output the same results.
In order to work around this, you need to either make sure your random is seeded uniquely each time, or share and use a single Random instance. The easiest option is to just make the Random instance static:
class YourClass
{
private static Random randomGenerator = new Random();
public YourClass(int entriesCount)
{
int weight = 0;
for (int i = 0; i < entriesCount; i++)
{
weight = randomGenerator.Next(10);
this.weights[i] = weight;
}
}
// .. rest of your class
This will cause the class to always reuse the same Random instance, so you'll get different values each time.
Note that if you're going to be using this in a multithreaded scenario, you'll also have to synchronize access to the random instance, or come up with a different approach (such as saving a seed value, and using something like Interlocked.Increment to increment it and seed a new random from each instance, etc).
Random is a pseudorandom number generator, which means the sequence of outputs is the same for any given seed. If you pass a seed to the constructor, you get a different sequence.
As far as I am aware, a random is seeded by the system time unless you specify otherwise. It generates numbers based on this number. As you create them almost exactly at the same time, they have the same seed and will almost always return the same number and sequence.
Any easy fix would be to create a static random all instances share, and just call .Next() on that static object.
From the MSDN documentation:
"using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers."

Categories

Resources