How can I pick a random entry from a list? - c#

I am using this code to pick a random element from a list:
var rand = new Random();
var i = rand.Next(words.Count);
keyword = words[i].keyword;
Is this the optimal way to do this or is there a better way that I could employ? What I am particularly concerned about is will this be completely random?

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.
Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
Hope this helps!!!

It will be absymally un-random, you must not create a new Random instance each time you need a number. Doing that completely ruins the statistical properties of the generator.
Even then you will not achieve perfect randomness (you need external hardware for that), but it ought to satisfy all the principal properties of randomness.

Put this line for single time initialization: var rand = new Random();
Use below code to generate new number each time.
var i = rand.Next(words.Count);
keyword = words[i].keyword;
Hope it will help you.

Related

Unity3d generate multiple random numbers

I am currently attempting to generate two random (whole) numbers at once for a game I am making. I am trying to randomly generate a start and end tile. When I do this though, my two randomly generated numbers are always the same. I understand this is probably just because they are being called calculated to close together, but I can't find any information that works on how to get two different random numbers. my code is quite simple (in c#):
float startTile = Mathf.Ceil(Random.Range(1.0f, 8.0f));
float endTile = Mathf.Ceil(Random.Range(1.0f, 8.0f));
Thank you in advance!
Edit
This was marked as a duplicate question, where the answer for the old question was:
Random rand = new Random();
int t = rand.next(x,x2);
Unless I'm doing something incorrect, I am unable to even use the rand.Next(x,x1) function within unity.
The actual code:
private void SpawnStartandEndTiles()
{
Random rand = new Random();
int t = rand.N //<Next is not an option
//Other misc. Code that uses the random numbers
}
Please let me know if I am just not getting something with how the Random function works.
Thanks so much.
First of all don't use System.Random because using most classes in System namespace (*) drastically increase the size of your game. Instead use UnityEngine.Random
Random numbers are always generated using a seed. Given a specific seed the sequence of random numbers are always the same. You can say computed random is never really random.
By setting the Random.seed to a value depending on the time makes Random.Range to generate numbers close to real random.
For example:
Random.seed = System.DateTime.Now.Millisecond;
//...
float startTile = Mathf.Ceil(Random.Range(1.0f, 8.0f));
float endTile = Mathf.Ceil(Random.Range(1.0f, 8.0f));
(*) These are in mscorlib.dll and therefore does not have any impact on the size of game
System.Collection.*
System.Collection.Generic.*
System.IO.*

Quickly generating random numbers in C#

I'm creating a program which creates several panels with randomly determined colors which will be incremented/decremented by some random constant every 20 milliseconds or so to create a smooth, undulating color. For this, I've just been using the Next(int) method of the Random class. For a single instance, this works perfectly--every time I run the program, I get different colors changing at different rates. The problem comes when I try to create multiple panels--most, if not all, come out looking and behaving identically to each other, implying that all of the randomly generated numbers were identical. I'm assuming that this is a result of generating all of the pseudorandom numbers in rapid succession, causing all of them to be based on the same seed.
Is there a better way than using the Random class to generate random integers in rapid succession to ensure that they're not identical? If there isn't any way already built into C#, is there any straightforward way to develop a pseudorandom number generator (bearing in mind that this is my first foray into using C#)?
Do not use multiple instances of the Random Class using the default constructor. If they all are initialized within the same time slice they will all have the same seed and will all generate the same sequence of random numbers, use the constructor that you can pass in a seed and pass a different seed to each instance.
Random rand0, rand1, rand2;
void init()
{
int baseSeed = (int) DateTime.Now.Ticks;
rand0 = new Random(baseSeed);
rand1 = new Random(baseSeed + 1);
rand2 = new Random(baseSeed + 2);
}
Also you only need one object per thread, use the same Random object for all of the panels if they are all on the same thread.
Random is fine if you don't need cryptographically secure random numbers - but chances are you're creating a new instance every time you need a number, rather than using one instance throughout.
When you create a new instance of Random it will take "the current time" as the seed - so if you create two in quick succession, you'll end up with two instances with the same seed and therefore the same numbers (when you use the same calls).
It's generally better to use a single instance of Random - or rather, one per thread, as it's not thread-safe.
See my article on the topic for various approaches.
If you have multiple instances of the Random class that are producing identical series of random numbers, then you must be creating each instance using the same seed. For example:
The most likely explanation for that is that you are creating them all like this:
var rng = new Random();
and creating each instance at the same point in time. This constructor uses the current time to seed the RNG and if you create them all at the same point in time, they will all be seeded with the same time.
Solve the problem by creating each instance with a different seed. Or create a single RNG and share it between all panels.
I prefer RNGCryptoServiceProvider. It is roughly as fast as Random and tends to produce more unique values in my informal testing. You also avoid any undesirable behaviors pertaining to seeding (such as others are describing).
However, you can't guarantee uniqueness (otherwise it wouldn't be random). You can use a database if you need to permanently track unique values (which it doesn't sound like you wish to do) or a Dictionary where the random value is the key if you just care about generating a set of unique numbers in memory. If the key already exists, you reject the value and generate another one.
using System.Security.Cryptography;
...
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
byte[] bytes = new byte[8];
crypto.GetBytes( bytes );
long value = BitConverter.ToInt64( bytes, 0 );
As mentioned above, you can use a single instance of the random class. However, if for some reason this isn't desirable (i.e. you want to run multiple threads and don't want any contention), then you can use multiple instances as long as you initialize the seed for each generator to a random or pseudo-randomly generated seed.
For this initial seed generation, you will need to use the same Random generator.

Creating a true random [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does it appear that my random number generator isn't random in C#?
How can I generate truly (not pseudo) random numbers with C#?
I've created a dice game where the dice is based on a percentile, 1-100.
public static void Roll()
{
Random rand = new Random((int)DateTime.Now.Ticks);
return rand.Next(1, 100);
}
But I don't feel like it's a real random based on current time.
If I do
for (int i = 0; i < 5; i++)
{
Console.WriteLine("#" + i + " " + Roll());
}
They would all be the same values, because the DateTime.Now.Ticks didn't change, it seeded the same number.
I was thinking I could generate a new random seed if the seed was the same due to the current time, but it doesn't feel like an honest "re-roll"
What should I do to try and replicate a close to real/honest dice roll? Should I use the RNGCryptoServiceProvider class to generate rolls instead?
DateTime.Now.Ticks only has a resolution of approximately 16ms, so if you create a Random with that overload multiple times within a 16ms "slot" they will all be seeded with the same value and therefore you will get the same sequence.
Initialize your Random outside your loop so that a single Random sequence is produced, rather than creating it each time within the loop which could result in Randoms being seeded with the same value and so produce the same sequence.
Update
My previous point that the default constructor initialized Random with CPU ticks was incorrect, the default constructor actually uses Environment.TickCount which is:
A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started.
Which still has a low resolution. If you make multiple instances of Random in quick succession, they can easily be created within the same time slot and therefore have the same seed value, and create the same sequence. Create a single instance of Random and use that.
Update
Further to your comments, if you wish to generate a random sequence across multiple threads, please see the following Jon Skeet article which discusses a thread-safe wrapper:
https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness
Pseudo-random number generators like Random should only be seeded once, so:
private static Random _rand = new Random();
public static int Roll()
{
return _rand.Next(1, 100);
}
(Note I made the return value int rather than void; the Roll function as quoted in the question results in a syntax error.)
But your title says "Creating a true random". Random won't do that for you, it's a pseudo-random number generator, meaning it's deterministic, just hard to predict if you don't know the seed. Usually that's good enough for most purposes, but if you need real randomness, you need an entropy source. http://random.org is one popular one.
You should create your Random class only once outside your Roll function and seed it with a unique value.
You are recreating your Random each time you call Roll which causes the 'not random numbers'.
Should I use the RNGCryptoServiceProvider class to generate rolls instead?
If this is a serious game with money at stake then: Yes.
I'm assuming that you are calling the Roll() method so quickly that Now.Ticks is the same?
The simplest way to get around this would be rather than to create a new Random() instance each time you call Roll() create a static variable to hold a single instance of Random().
The usual way to use random number generators is to seed them once, save them and call on them repeatedly throughout your programme. As long as you seed from a suitable value at the start, you should get acceptable randomness - assuming the generator you're using is using a function returning things which are suitably random for your purposes. So, save your Random instance outside the Roll() function, seed it the first time it's used, then just call Next() on it each time you need another number.
When you get right down to it, there's no such thing as true random number generation on a computer, only pseudorandom sequences based on a seed. However, humans are terrible at identifying randomness, so it's usually okay.

Random numbers for dice game [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
random string generation - two generated one after another give same results
I am writing a simple dice game for windows phone 7, that involves rolling two dice at the same time. Here is my Dice Roll Code:
private int DiceRoll()
{
int result;
Random rnd = new Random();
result = rnd.Next(1, 7);
return result;
}
I then have this code that rolls the dice when a button is clicked:
private void roll_Click(object sender, RoutedEventArgs e)
{
roll1 = DiceRoll();
roll2 = DiceRoll();}
My problem is that both die get the same result.
Any idea how I can get a rolling algorithm that will usually return different results, but occasionally return the same?
The default seed for Random is based on the current time. To quote the documentation,
As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.
That is exactly what you should do: create one instance of Random and use it to generate all your random numbers.
You need to keep one Random object around and reuse it; every time you create a new Random object, you effectively reset the sequence of numbers to begin in the same place. Store the Random object as a member variable someplace. You'll also want to seed it with a different value each time you run the program -- for example, a value based on the system clock time.
The clear majority of 'random number' tools I've seen fail badly if you allocate two or more random objects in a single application. You're allocating a new Random object for every invocation, and each time they are going to be seeded with something pretty weak, and maybe even identical seeds.
So, generate a single Random object and use it over the life of your application.

random string generation - two generated one after another give same results

I have a simple piece of code:
public string GenerateRandomString()
{
string randomString = string.Empty;
Random r = new Random();
for (int i = 0; i < length; i++)
randomString += chars[r.Next(chars.Length)];
return randomString;
}
If i call this function to generate two strings, one after another, they are identical... but if i debug through the two lines where the strings are generated - the results are different.
does anyone know why is it happening?
This is happening, because the calls happen very close to each other (during the same milli-second), then the Random constructor will seed the Random object with the same value (it uses date & time by default).
So, there are two solutions, actually.
1. Provide your own seed value, that would be unique each time you construct the Random object.
2. Always use the same Random object - only construct it once.
Personally, I would use the second approach. It can be done by making the Random object static, or making it a member of the class.
The above answers are correct. I would suggest the following changes to your code though:
1) I would suggest using a StringBuilder instead of appending to the string all the time. Strings are immutable, so this is creating a new string each time you add to it. If you have never used StringBuilder, look it up. It is very useful for this sort of work.
2) You can make your method easier to reuse if you pass the length into the method itself. You could probably pass the chars array in as well, but I've left that out.
3) Use the same random object each time, as suggested above.
public string GenerateRandomString(int length)
{
StringBuilder randomString = new StringBuilder(length);
for (int i = 0; i < length; i++)
randomString.Append(chars[(int)(_RandomObj.Next(chars.Length))].ToString());
return randomString.ToString();
}
It's because you're creating two random objects at the same time. This is giving it the same seed, so you're going to get the same numbers.
When you debug it, there's time between the creation of the random objects which allow them to get different seeds.
The default constructor for Random (the one you're using) seeds the generator with a value based on the current time. If the time in milliseconds doesn't change between the first and second call of the function, it would use the same random seed.
My suggestion is to use a static Random object and only initialize it once.
Since the Random generator is tied with the system clock you are probably displaying the same results with that time period. There are several ways to correct. If you are using loops place the Random rnd = new Random(); outside of the loop.
Place the Random rnd = new Random(); line where you declare your variables and use the same variable throughout your program (rnd for this example).
This will work in most cases.

Categories

Resources