I am currently working with generating a random number(1-20) and counting the number of times each number has been randomly generated. In textBox1 I choose the amount of numbers I want to generate. I display the final results in a multiline textBox2. The problem I am experiecing is that every time I click the button again it resets the count of times a number has been randomly generated.
Is there away i can click the button an x amount of times and count the times a number has been randomly generated without resetting the count? I am trying to this specifically with the help of an array.
Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random r = new Random();
private void button1_Click(object sender, EventArgs e)
{
var n = int.Parse(this.textBox1.Text);
var y =
Enumerable
.Range(0, n)
.Select(x => r.Next(20) + 1)
.ToArray();
var sum = y.Sum();
var avg = (double)sum / (double)n;
var frequency = y.ToLookup(x => x);
textBox2.Text = String.Join(Environment.NewLine, new[]
{
"Number of times an integer was randomly generated",
String.Format("{0} {1}", sum, avg),
}.Concat(Enumerable
.Range(1, 20)
.Select(x => String.Format("{0} ({1})", x, frequency[x].Count()))));
}
}
The scope of your variable lives only inside the
button1_Clickmethod. You need to move it out as a private class variable in order to persist it across clicks. It’ll require some minor refactoring of your code in order to get there.Note that the upper bound of the
rand.next(min,max)method is exclusive, so that means in order to generate numbers from 1 to 20, you need to pass it 1 to 21. Not sure why the inconsistency there–it’s a little confusing.Output for n = 10