开发者

Random generation problem

I know this is such an old thing and I have searched l开发者_如何学Cike 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.


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.
}


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)];
        }

    }
}


Don't create a new Random object each time.

get rid off

 rand = new Random();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜