How to randomize seed in C# [duplicate]

醉酒当歌 提交于 2020-03-15 07:51:31

问题


I need to generate random int in C#. I am using clock time to set the seend. However, as the rnd.Next() function may take less than a millisecond, this does not work if one has to generate a list of ints.

        for( int i=0; i<5; i++) {
            int max_val = 10; // max value
            var rnd = new Random(DateTime.Now.Millisecond);
            int randind = rnd.Next(0, max_val);
            Console.WriteLine(randind);
        }

Output:
1 5 5 5 5

How can one randomise the seed in a clean way without adding an ugly sleep?


回答1:


Create your Randomobject outside the loop and don't provide the seed parameter -- one will be picked for you. By taking it out of the loop, rnd.Next() will give you a random sequence anyway.

   var rnd = new Random();     
   for( int i=0; i<5; i++) {
        int max_val = 10; // max value
        int randind = rnd.Next(0, max_val);
        Console.WriteLine(randind);
    }



回答2:


The Guid Object guaranties a different result each time. You could do this:

... new Random(Guid.NewGuid().GetHashCode())



来源:https://stackoverflow.com/questions/39105924/how-to-randomize-seed-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!