Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number generation:returning same number in C# if I run. alright if Debug step by step

Tags:

c#

I am having problem with random number generation in c#. If I RUN this form application directly, the random number generation is same for all.

If i DEBUG this line by line by pressing F10, then it will generate different random numbers. Why this is happening? What should I do to generate different random numbers?

Greyhound.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ADayAtTheRaces
{
    class Greyhound
    {
        int location=0;
        Random randomize = new Random();

        public int run()
        {
            location = randomize.Next(0, 100);
            return location;
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ADayAtTheRaces
{
    public partial class Form1 : Form
    {
        Greyhound[] greyHound = new Greyhound[4];
        ProgressBar[] progressBar = new ProgressBar[4];
        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < 4; i++)
            {
                greyHound[i] = new Greyhound();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= 3; i++)
            {
                progressBar[i].Value = greyHound[i].run();
            }
        }
    }
}
like image 502
SHRI Avatar asked Feb 09 '12 13:02

SHRI


People also ask

Why is rand () giving me the same number?

This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.

How do I get the same random number in C?

The rand() and srand() functions are used to generate random numbers in C/C++ programming languages. The rand() function gives same results on every execution because the srand() value is fixed to 1. If we use time function from time.

Can random numbers repeat?

No, while nothing in computing is truly random, the algorithms that are used to create these "random" numbers are make it seem random so you will never get a repeating pattern.


1 Answers

Don't instantiate a new Random object each time, instead use it as a static member:

class Greyhound
{
    static Random randomize = new Random();
    int location=0;

    public int run()
    {
        location = randomize.Next(0, 100);
        return location;
    }
}

See Random.Next returns always the same values

like image 164
ken2k Avatar answered Jan 04 '23 02:01

ken2k