1

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);
    }
Community
  • 1
  • 1
edgarmtze
  • 24,683
  • 80
  • 235
  • 386

3 Answers3

6

You should pass the Random as parameter to your function. Although your function has no added value then anymore.

var rnd = new Random();
for (int i = 0; i < 20; i++)
{
    randomNumber = RandomNumber(rnd ,0, 617);
    c += "a " + randomNumber + ", ";                    
}

public static int RandomNumber(Random rnd, int min, int max)
{
    return rnd.Next(min, max);
}

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 single Random instance 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>:

HashSet<int> uniqueNumber = new HashSet<int>();
var rnd = new Random();
while(uniqueNumber.Count<20){
    var nextNum = rnd.Next(0, 617);
    uniqueNumber.Add(nextNum);
}
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

The instance of Random needs to be instantiated once.

static Random random = new Random();
public static int RandomNumber(int min, int max)
{        
    return random.Next(min, max);
}

In your implementation, random was getting instantiated with the system clock several times for one unit of time so you're using the exact same seed value for very few iterations, which for a single call means you'll always get the same value from Next.

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
0

Put the Random outside of RandomNumber i.e.

static Random random = new Random();
public static int RandomNumber(int min, int max)
{
    return random.Next(min,max);
}
NominSim
  • 8,447
  • 3
  • 28
  • 38