-3

I have an array of strings that I want to pick one variable randomly from the list. Although I am using random function but I would like to know whether it will pick value zero ever or not? (Element zero from my array)

string randomString = a[new Random().Next(a.Length)]; 
CowBoy
  • 185
  • 5
  • 19

3 Answers3

3

Random should be random, so getting an A should be Random

One thing to note is if you're calling

string randomString = a[new Random().Next(a.Length)];

in quick succession e.g. in a loop, then create a class field, else Next() will be the same.

private Random _random = new Random();

then in your function call

string randomString = a[_random.Next(a.Length)];
ASG
  • 957
  • 9
  • 20
2

The Random class simply uses pseudorandom number generation to give you a number that fits your specifications and seems random. Your code is fine, but with (in theory) 26 possible results, getting one of them shouldn't occur too often.

I believe the issue you're experiencing is that you're creating new Random objects in a loop, and they're ending up with the same seed, try declaring it in your class:

Random rnd = new Random();

And using it like so:

string randomString = a[rnd.Next(a.Length)];

The benefit of using this (as opposed to your current method) is that if you run it inside a loop you don't risk getting the same answer multiple times in a row.

Hope this helped, cheers!

~Winderps

Winderps
  • 100
  • 9
1

How can you say rarely?

try this:

        String[] myArray = new String[] { "A", "B", "C" };

        Random rd = new Random();

        Int32 aCounter = 0;
        Int32 bCounter = 0;
        Int32 cCounter = 0;

        for (int i = 0; i < 25000; i++)
        {
            Int32 retVal = rd.Next(myArray.Length);
            switch (retVal)
            {
                case 0:
                    aCounter++;
                    break;
                case 1:
                    bCounter++;
                    break;
                case 2:
                    cCounter++;
                    break;
            }
        }

As expected in my test, as expected aCounter, bCounter and cCounter always have same values between 8000 and 8500.

Perahps you called your new Random().Next() too soon use a single object Random and call Next() each time on the same object

Francesco Milani
  • 415
  • 4
  • 11
  • Thank you for the comment, I mainly want to know how random() itself works? Does it choose a number between 0 to 1 randomly and then multiply it by another value? – CowBoy Feb 03 '14 at 13:55
  • Basically a Random it's an object built on a seed value. You can decide to call the constructor with your own seed or without. each times you call an overload of the Next() method it applys some calculation starting from the seed. Take a look at the official documentation http://msdn.microsoft.com/en-us/library/System.Random(v=vs.110).aspx – Francesco Milani Feb 03 '14 at 14:06