Possible Duplicate:
Random number generator not working the way I had planned (C#)
I have this code in c# but I get a result the same number, what is it wrong?
like a21, a21, a21….
String c = "";
int randomNumber = 0;
for (int i = 0; i < 20; i++)
{
randomNumber = RandomNumber(0, 617);
c += "a " + randomNumber + ", ";
}
file.WriteLine(c);
I am using this function
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
You should pass the
Randomas parameter to your function. Although your function has no added value then anymore.Every time you do
new Random()it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a singleRandominstance and keep using Next on the same instance.https://stackoverflow.com/a/768001/284240
Edit: i read in your comment that you want to create 20 unique numbers in the given range, here is one way using
HashSet<int>: