2

I've run into a strange issue. When I run the following code, each of my text boxes get's filled with the same randomly generated number.

public void diceAdd()
    {
        int[] die = new int[4];
        for(int i = 0; i < total.Length; i++)
        {
            for (int r = 0; r < die.Length; r++)
            {
                //Simulates rolling a 6 sided die
                Random rand = new Random();
                randomNumber = rand.Next(1, 7);
                die[r] = randomNumber;
            }
            int smallest = die[0];
            for (int c = 1; c < die.Length; ++c)
            {
                if (die[c] < smallest)
                {
                    smallest = die[c];
                }
            }
            total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
        }
        strTxt.Text = total[0].ToString();
        dexTxt.Text = total[1].ToString();
        conTxt.Text = total[2].ToString();
        intTxt.Text = total[3].ToString();
        wisTxt.Text = total[4].ToString();
        chaTxt.Text = total[5].ToString();

The thing is, if I add this messagebox

MessageBox.Show(i.ToString());

after

total[i] = die[0] + die[1] + die[2] + die[3] - smallest;

the numbers each get unique outputs, as intended.

I'm thinking it has something to do with threading, but figured I'd ask here before messing something up.

Dylan
  • 47
  • 6

1 Answers1

4

you are recreating the random number generator every time in the loop, create one before the loop:

  Random rand = new Random();

  for(int i = 0; i < total.Length; i++)
  {
    ...
  }

see also here and here, it explains why the numbers don't change

Community
  • 1
  • 1
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110