-1

I know this is such an old thing and I have searched like every website for an answer before I post this but I couldn't find a solution

I am using C# - Windows Forms

and I have this peice of code :

char[] options = { 'a', 'l', 'w' };

and I also have this function :

static Random rand = new Random();
    static char OptionPicker(char[] options)
    {
        rand = new Random();
        return options[rand.Next(0, 2)];
    }

my problem is that when I want to navigate through an array of chars and execute the previous function on each of this array

I get the same option picked and it doesn't get randomed ?

can you tell me how to do it ? Best Regards.

Johan
  • 74,508
  • 24
  • 191
  • 319
  • possible duplicate of [C# Random generation](http://stackoverflow.com/questions/4528066/c-random-generation) – H H May 29 '11 at 17:11
  • -1 because this is a 1000-times dupe and several dupes are in the Related list. Exact title matches. – H H May 29 '11 at 17:12

4 Answers4

5

Remove the rand = new Random(); line, you're creating the same object twice. rand.Next(0, 3) is enough to generate new random numbers. Also make sure that your upper bound is '3' not '2' since it is exclusive.

static Random rand = new Random();
static char OptionPicker(char[] options)
{
    return options[rand.Next(0, 3)]; // 3 is exclusive so results will be 0,1,2 only.
}
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
2

A couple of things. You need to either not recreate the Random object each time or recreate it with a different Seed Value (in my sample I only create it once and tie the seed value to to the present time/milliseconds.)

A you should range your select based on the actual length of the array, rather than hardcoding to 2..

Try this: (in a console app)

namespace SO_Console_test
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] options = { 'a', 'l', 'w' };
            Random rand = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i <= 100; i++)
            {
                Console.WriteLine(OptionPicker(options,rand).ToString());
            }
            Console.ReadLine();
        }


        public static char OptionPicker(char[] options, Random rand)
        {
            return options[rand.Next(0, options.Length)];
        }

    }
}
Cos Callis
  • 5,051
  • 3
  • 30
  • 57
0

Don't create a new Random object each time.

get rid off

 rand = new Random();
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108
0

Remove rand = new Random() - re-creating it in quick succession as you are makes it give you the same value each time.

Steve Wilkes
  • 7,085
  • 3
  • 29
  • 32