C # code gives only expected results in step?

So I have a die roll application ...

When I look at the code, it functions normally, and the "results" contain the correct number of throw results, and they seem random when I leave the code to run and do exactly the same thing that it creates a set of identical numbers.

I am sure that this is a logical mistake that I do not see, but messing with it for several hours did not improve the situation, so any help is significant. :)

    class Dice
{

    public int[] Roll(int _throws, int _sides, int _count)
    {
        Random rnd = new Random();
        int[] results = new int[_throws];
        // for each set of dice to throw pass data to calculate method
        for (int i = 0; i < _throws; i++)
        {
            int thisThrow = Calculate(_sides, _count);
            //add each throw to a new index of array... repeat for every throw
            results[i] = thisThrow; 
        }

        return results;
    }


    private int Calculate(int _sides, int _count)
    {
        Random rnd = new Random();
        int[] result = new int[_count];
        int total = 0;
        //for each dice to throw put data into result
        for (int i = 0; i < _count; i++)
        {
            result[i] = rnd.Next(1, _sides);
        }
        //count the values in result
        for (int x = 0; x < _count; x++)
        {
            total = total + result[x];
        }
        //return total of all dice to Roll method
        return total;
    }
}
+5
source share
5 answers

: Random, .

+12

"Random rnd = new Random();" . ( ), - .

1 Random , .

+5

, . .

: FROM MSDN

, , .

, , , .

. Random...

+1

, ...

Random , , , .. - , System.Security.Cryptography.RandomNumberGenerator. .

        RandomNumberGenerator gen = RandomNumberGenerator.Create();
        byte[] myBytes = new byte[4];
        gen.GetBytes(myBytes);
        int myValue = (BitConverter.ToInt32(myBytes, 0));

, . , Random. , Random, .

EDIT: , . :

1,000,000 : RandomNumberGenerator: 2,6 :.015 .

, Random 150 .

+1

Random . .

http://msdn.microsoft.com/en-us/library/aa329890%28VS.71%29.aspx

Random r = new Random(DateTime.Now.Millisecond);
-1

All Articles