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.
Related
This question already has answers here:
C# Select random element from List
(7 answers)
Randomize a List<T>
(28 answers)
Closed 3 months ago.
I need to generate a random string from a pool of 6 pre-generated strings.
I created a list, but I don't understand how to use "random" to generate one random string out of that list.
This is what I have so far:
string RandomPowerSentence()
{
Random rnd = new Random();
List<string> powerStrings = new List<string>()
{
"You are kind!",
"You are beautiful!",
"You are smart!"
};
//I assume that here I put the code that generates a random string out of the list with rnd
return "the random string from the list";
Help will be very appreciated!
I used the random class, but I don't understand/know how to use it with strings and not ints.
This is one solution:
string RandomPowerSentence()
{
Random rnd = new Random();
int myRandomNumber;
List<string> powerStrings = new List<string>()
{
"You are kind!",
"You are beautiful!",
"You are smart!",
"You are awesome!",
"You are funny!",
"You're a f*cking A!"
};
// rnd.Next(int, int) Returns a positive random integer within the specified minimum and maximum range (includes min and excludes max).
myRandomNumber = rnd.Next(0, powerStrings.Count);
return powerStrings[myRandomNumber];
}
An explanation of the usage of "Random()": https://www.tutorialsteacher.com/articles/generate-random-numbers-in-csharp
An explanation of the usage of "Count": https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.count?view=net-7.0
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.
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#?
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 6 years ago.
So I coded a quick program to test how much difference it would make (in terms of processing speed) to check a boolean inside a foreach statement compared to checking it in a conditional statement outside of the loop. To test this I made a function generate random strings and add them to a list, but the for loop that generates the strings seems to advance too quickly without generating different strings in ever repetition. To fix this I added a Thread.Sleep(15) (15 milliseconds seems to be the minimum required to generate a different string in every repetition).
My question is this: is it possible to fix this issue without a Thread.Sleep(15)? Waiting 15 milliseconds between every repetition makes it so that the program takes a way bigger amount of time to run, which makes it highly unpractical for it's purpose (if I want to get statistically relevant data I'd have to run it around 10 thousand times for each option (the "good" and the "bad" way)). Here's the for loop in question:
for (int i = 0; i < 1000; i++) {
var stringChars = new char[8];
var random = new Random();
for (int n = 0; n < stringChars.Length; n++)
{
stringChars[n] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
data.Add(finalString);
Thread.Sleep(15);
}
The problem you are getting is that you are recreating the Random class each time you iterate the loop.
The reason this is a problem is because the default seed for the Random class is the current system timestamp, which on repeated iterations could well be the same value.
Creating the Random outside of the for loop will ensure that a pseduo-random sequence is generated as you would expect.
Try this:
var random = new Random();
for (int i = 0; i < 1000; i++) {
var stringChars = new char[8];
for (int n = 0; n < stringChars.Length; n++)
{
stringChars[n] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
data.Add(finalString);
}
This question already has answers here:
Direct array initialization with a constant value
(6 answers)
Fastest way to fill an array with a single value [duplicate]
(3 answers)
Closed 8 years ago.
I'd like to declare an array of int rows with a variable size (X) and init all values to 1. For the moment I use this :
int[] rows = new int[X];
for (int i = 0; i < rows.Length; i++)
{
rows[i] = 1;
}
Is there any faster/shorter way to do it with some sort of fill(1) or int[] rows = new int[X] {1}; ?
LINQ:
int[] rows = Enumerable.Repeat(element:1, count: X).ToArray();// named parameter - X
// doesn't tell anything