so I've just started learning C# and I got across this exercise that rolls a die N times and then print the number of times each side is rolled. I got the answer however, my question lies on instantiating a Random
number object before the loop and in the loop.
my code goes like this (this is instantiation before the loop):
static void DiceRoll(int RollTimes)
{
int roll = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
Random rnd = new Random();
for (int ctr = 0; ctr < RollTimes; ctr++)
{
roll = 0;
roll = (int)rnd.Next(1, 7);
switch (roll)
{
case 1:
counter1++;
break;
case 2:
counter2++;
break;
case 3:
counter3++;
break;
case 4:
counter4++;
break;
case 5:
counter5++;
break;
case 6:
counter6++;
break;
}
}
Console.WriteLine("1 is rolled {0} times.", counter1);
Console.WriteLine("2 is rolled {0} times.", counter2);
Console.WriteLine("3 is rolled {0} times.", counter3);
Console.WriteLine("4 is rolled {0} times.", counter4);
Console.WriteLine("5 is rolled {0} times.", counter5);
Console.WriteLine("6 is rolled {0} times.", counter6);
}
and the result is like this:
1 is rolled A times.
2 is rolled B times.
3 is rolled C times.
4 is rolled D times.
5 is rolled E times.
6 is rolled F times.
before I got that right, the instantiation line (Random rnd = new Random();
) was in the loop.
for (int ctr = 0; ctr < RollTimes; ctr++)
{
roll = 0;
roll = (int)rnd.Next(1, 7);
Random rnd = new Random();
// rest of the code
then the result (at random):
1 is rolled (N) times.
2 is rolled (N) times.
3 is rolled (N) times.
4 is rolled (N) times.
5 is rolled (N) times.
6 is rolled (N) times.
Can somebody explain or enlighten me why the position of instantiation alters the result? Thanks!