Tuesday 20 August 2019

checkbox - How to randomly fill checkboxes in c# - Visual Studio





So this is my first question on . I'm working on a drum sequencer and want to implement a button to randomly fill the 80 checkboxes that indicate a drum sound being triggered. Currently what I have only filles one box of the 80 randomly, but I want each of them to have a random chance of being filled. The first part of my code simply clears the current selection. Here is my attempt in the following code:



private void button4_Click(object sender, EventArgs e)
{
List Checkboxlist = new List();
foreach (CheckBox control in this.Controls.OfType())

{
Checkboxlist.Add(control);
control.Checked = false;
}

for (int i = 0; i <= 200; i++)
{
var random = new Random();
var r = random.Next(0, Checkboxlist.Count);
var checkbox = Checkboxlist[r];

checkbox.Checked = true;
}
}


Thank you for looking!


Answer



Don't create new Random() inside the loop. It is better to declare the random once, the best way is to create it as static member.



private static Random random = new Random(); // Class member


private void button4_Click(object sender, EventArgs e)
{
List Checkboxlist = new List();
foreach (CheckBox control in this.Controls.OfType())
{
Checkboxlist.Add(control);
control.Checked = false;
}


for (int i = 0; i <= 200; i++)
{
var r = random.Next(0, Checkboxlist.Count);
var checkbox = Checkboxlist[r];
checkbox.Checked = true;
}
}


The reason for that is:





The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value,




Source



The rapid for-loop cause the Random to be created with the same seed, so the Next function returned the same first value of the series of numbers.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...