Ahmed
Ahmed

Reputation: 525

Strange behavior when implementing monte carlo simulation in C#

I'm trying to implement Monte Carlo Simulation in C# windows form application using Weighted Quick Union With Path Compression method. Firstly I take gridSize and then generate a grid equals to gridSize * gridSize and consists of black background labels that represent sites, then I randomly union some sites and make their background in white. The problem is whenever I run the project, I get the whole sites in black -no matter how many times I try-, but if I added breakpoints and proceeded step by step, I get some white sites as intended!!!

Here is the code:

public partial class Form1 : Form
{
    int gridSize = 0;
    byte siteSize = 50;
    FlowLayoutPanel flowLayoutPanel;
    UnionFind uf;
    int randomFirstNumber;
    int randomSecondNumber;
    string labelName = string.Empty;
    Random rnd = new Random();
    int numberOfAttempts;
    Label label;
    HashSet<int> excludeHashSet = new HashSet<int>();

    public Form1()
    {
        InitializeComponent();
    }

    private void setGridSizeButton_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(gridSizeTextbox.Text) && int.TryParse(gridSizeTextbox.Text, out gridSize))
        {
            if (gridSize > 0)
            {
                var flowLayoutPanel = createFlowLayoutPanelAndLabels();

                setGridSizeButton.Enabled = false;
                gridSizeTextbox.Enabled = false;

                randomlyUnionSitesAndWhiteThem();
            }
        }
    }

    private void reset_Click(object sender, EventArgs e)
    {
        setGridSizeButton.Enabled = true;
        gridSizeTextbox.Enabled = true;
        gridSizeTextbox.Text = string.Empty;
        flowLayoutPanel.Dispose();
        excludeHashSet = new HashSet<int>();
        gridSizeTextbox.Focus();
    }

    private FlowLayoutPanel createFlowLayoutPanelAndLabels()
    {
        flowLayoutPanel = new FlowLayoutPanel();
        flowLayoutPanel.Name = "flowLayoutPanel";
        flowLayoutPanel.Location = new Point(30, 60);
        flowLayoutPanel.Size = new Size(gridSize, gridSize);
        flowLayoutPanel.BorderStyle = BorderStyle.Fixed3D;
        flowLayoutPanel.Width = siteSize * gridSize + 10 * gridSize;
        flowLayoutPanel.Height = siteSize * gridSize + 10 * gridSize;

        for (int i = 0; i < gridSize * gridSize; i++)
        {
            var label = new Label();
            label.Text = "";
            label.Name = i.ToString();
            label.Width = siteSize;
            label.Height = siteSize;
            label.BackColor = Color.Black;
            label.Margin = new Padding(3);
            label.BorderStyle = BorderStyle.FixedSingle;

            flowLayoutPanel.Controls.Add(label);
        }
        this.Controls.Add(flowLayoutPanel);

        return flowLayoutPanel;
    }

    private void randomlyUnionSitesAndWhiteThem()
    {
        uf = new UnionFind(gridSize * gridSize);

        numberOfAttempts = rnd.Next(0, gridSize * gridSize);
        for (int i = 0; i < numberOfAttempts; i++)
        {
            randomFirstNumber = getRandomNumber(0, gridSize * gridSize, excludeHashSet);
            randomSecondNumber = getRandomNumber(0, gridSize * gridSize, excludeHashSet);

            labelName = uf.union(randomFirstNumber, randomSecondNumber).ToString();
            if (Convert.ToInt16(labelName) > -1)
            {
                label = (Label)flowLayoutPanel.Controls.Find(labelName, false).First();
                label.BackColor = Color.White;
                excludeHashSet.Add(Convert.ToInt16(labelName));
            }
        }
    }

    private int getRandomNumber(int min, int max, HashSet<int> excludes)
    {
        int randomNumber;
        do
        {
            var range = Enumerable.Range(min, max).Where(i =>  !excludes.Contains(i));

            var rand = new Random();
            int index = rand.Next(0, max - excludes.Count);

            randomNumber = range.ElementAt(index);
        }
        while (excludes.Any(x => x == randomNumber));

        return randomNumber;
    }
}

And this is my Union method:

class UnionFind
{
    .....
    public int union(int firstNumber, int secondNumber)
    {
        firstNumber = getRoot(firstNumber);
        secondNumber = getRoot(secondNumber);

        if (firstNumber == secondNumber)
        {
            return -1;
        }

        if (sizes[firstNumber] < sizes[secondNumber])
        {
            array[firstNumber] = secondNumber;
            sizes[secondNumber] += sizes[firstNumber];

            return array[firstNumber];
        }
        else
        {
            array[secondNumber] = firstNumber;
            sizes[firstNumber] += sizes[secondNumber];

            return array[secondNumber];
        }
    }
    .....
}

Upvotes: 1

Views: 191

Answers (3)

Ahmed
Ahmed

Reputation: 525

I figured out the reason for the strange behavior. This happens when using Random class inside a loop so many times. This can be solved with multiple methods.

For example System.Threading.Thread.Sleep(10);. Here you are making loop sleep for n milliseconds.

private int getRandomNumber(int min, int max, HashSet<int> excludes)
{
    int randomNumber;
    do
    {
        System.Threading.Thread.Sleep(10);
        ...

This can also be achieved using System.Timers.Timer which will yield the same result. Also this method is more suited for such problem.

System.Timers.Timer myTimer = new System.Timers.Timer();

private void percolateEverySecond()
{
    myTimer.Elapsed += new ElapsedEventHandler(percolateForTimer);   //this is the function that will be executed every myTimer.Interval
    myTimer.Interval = 1000;
    myTimer.Enabled = true;
}

private void percolateForTimer(object source, ElapsedEventArgs e)
{
    //randomly white site, then union it with surrounding sites
    ...
}

private void Start_Click(object sender, EventArgs e)
{
    ...
    percolateEverySecond();
}

See this for more information about System.Threading.Thread.Sleep() vs System.Timers.Timer.

Also, note that the above code in the question have a huge room for improvements, but as a general rule, you should make every function responsible for only one specific task "Single Responsibility Principle".

Upvotes: 0

alex
alex

Reputation: 331

You have declared a new Random object in your getRandomNumber method who is always giving you the same value; if you use your atribute rnd instead it's works.

Here is the explanation

Upvotes: 1

alex
alex

Reputation: 331

You just have to call to this.Refresh() method at the end of your randomlyUnionSitesAndWhiteThem() method ;)

Upvotes: 0

Related Questions