0

I've encountered a strange problem with a c# program. The purpose of the program is to roll dice and display their outputs. The Logic for the program is fine and only works for reason when I output to a message box. Here's teh code:

private void btnRoll_Click(object sender, EventArgs e)
    {
        lbDice.Items.Clear();
        int[] rolls = new int[13];
        for (int i = 1; i < numTxt.Value; i++) {
            int index = new Random().Next(1, 7) + new Random().Next(1, 7);
            //MessageBox.Show(index + ""); THIS LINE IS REQUIRED
            rolls[index] += 1;
        }
        updateList(rolls);
    }


    public void updateList(int[] rolls)
    {
        for (int i = 1; i < rolls.Length; i++)
        {
            lbDice.Items.Add("" + i + "  " + rolls[i]);
        }
    }

If it's not there, the program will only add 1 to each index.

Tessa Painter
  • 2,113
  • 2
  • 16
  • 21

2 Answers2

1

From my experience, this is related to how the Random class generates random numbers. Doing new Random() more than once could create the same value for each case.

trying creating the Random class instance only once:

Random rand = new Random();
for (int i = 1; i < numTxt.Value; i++) {
    int index = rand.Next(1, 7) + rand.Next(1, 7);
    rolls[index] += 1;
}

As an experiment, you could replace the MessageBox line with a Sleep and see if that also works

Tee
  • 414
  • 2
  • 8
  • 19
0

No need to create a Random instance every time. Keep it and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

This code (below) may help you.

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please provide a number and press 'Enter'");
            var input = Console.ReadLine();

            int lenght;
            if (!int.TryParse(input, out lenght))
            {
                lenght = 10;
            }
            int l = 13;
            int[] rolls = new int[l];

            var rnd = new Random();

            for (int i = 1; i < lenght; i++)
            {
                int index = rnd.Next(1, 7) + rnd.Next(1, 7);
                //MessageBox.Show(index + ""); THIS LINE IS REQUIRED
                rolls[index] += 1;
            }

            for (int i = 0; i < l; i++)
            {
                Console.WriteLine($"rolls[{i}] = {rolls[i]}");
            }

            Console.WriteLine("Done. Prss any key to exit");
            Console.ReadKey();
        }
    }
}

Overall I think this is related to this question

Good luck!

Community
  • 1
  • 1
Pavel Kovalev
  • 7,521
  • 5
  • 45
  • 67