C# Random Numbers [closed]
Ok, So Im using int indexSelector = RandomNumber(1, 14);
to create a random number and pull the matching index out of an array. But it seems to only be calling 3 or 4 numbers. Like the items being pulled out are very similar.
Whats going on?
It sounds like you are calling a function which re-creates a Random object on each call. Don't re-create your Random object on each function call.
So do something like this:
private Random random = new Random();
public int RandomNumber(int min, int max)
{
return random.Next(min, max);
}
Make your random variable static:
static Random random = new Random();
Per Brian's suggestion, define your Random
object somewhere where it won't be recreated:
Random r = new Random();
And use this to get the number:
int indexSelector = r.Next(1, 14);
Random
if provided by the same seed, always returns the same sequence of numbers. I suggest you initialise your Random using a seed:
Random r = new Random(Environment.TickCount);
Or even better:
Random r2 = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
This ensures that you create a really random number sequence. If you do not send a seed, system will use a time dependent seed which will be the same if you create them immediately after each other.
精彩评论