在C#中实现蒙特卡罗模拟时的奇怪行为
本文关键字:模拟 实现 蒙特卡罗 | 更新日期: 2023-09-27 17:59:06
我正在尝试使用带路径压缩的加权快速并集方法在C#窗体应用程序中实现蒙特卡罗模拟。首先,我取gridSize
,然后生成一个等于gridSize * gridSize
的网格,该网格由代表站点的黑色背景标签组成,然后我随机联合一些站点,并将其背景设为白色。问题是,每当我运行项目时,无论我尝试了多少次,我都会得到黑色的整个网站,但如果我添加断点并一步一步地进行,我会得到一些白色网站!!!
这是代码:
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;
}
}
这是我的Union
方法:
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];
}
}
.....
}
您在getRandomNumber方法中声明了一个新的Random对象,该对象总是给您相同的值;如果你使用你的atribute rnd,它是有效的。
以下是
您只需要调用即可。在randomlyUnionSitesAndWhiteThem()方法末尾的Refresh()方法;)
我找到了奇怪行为的原因。当在循环中多次使用Random
类时,就会发生这种情况。这可以通过多种方法来解决。
例如CCD_ 5。在这里,您正在使睡眠循环n毫秒。
private int getRandomNumber(int min, int max, HashSet<int> excludes)
{
int randomNumber;
do
{
System.Threading.Thread.Sleep(10);
...
这也可以使用System.Timers.Timer
来实现,其将产生相同的结果。这种方法也更适合于这样的问题。
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();
}
有关System.Threading.Thread.Sleep()
与System.Timers.Timer
的更多信息,请参见此。
此外,请注意,问题中的上述代码有很大的改进空间,但作为一般规则,您应该使每个功能只负责一项特定任务"单一责任原则"。