Search code examples
c#visual-studioclassrandommessagebox

C# counting repeating numbers


I need a way to find and count the repeating numbers of this RNG.

So when I press the button like 500 times it need to count the times the same number apeared any ideas ? (Build in Visial Studio 2017 C#)

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

namespace Alpha_rng
{
public partial class RNG : Form
{
    private int number;
    public RNG()
    {
        InitializeComponent();
    }

    public int tal { get; private set; }

    private void button1_Click(object sender, EventArgs e)
    {
        Random slumpGenerator = new Random(); 
        int tal;
        tal = slumpGenerator.Next(0, 1000);
        textBox1.Text = tal.ToString();
        if (tal <=  10)
            MessageBox.Show ("Nat 5");
        if (tal >= 11 && tal <= 100) 
            MessageBox.Show("Nat 4");
        else 
            MessageBox.Show("Nat 3");
    }
  }
}

Solution

  • Simple:

    • create an empty list
    • during each loop: store the random number in that list

    And then; either during each iteration; or after your 500 runs: iterate that list; and look for the information you need. You could for example sort the list; and then see if you have "sublists" with the same value.

    Creating a list can be as easy as:

    List<int> list = new List<int>();
    list.Add(2);
    

    See here for examples on lists.

    Beyond that; you could of course use "advanced" things; such as maps. The map key represents the random value; and the map value would be a counter. In other words: you draw a number; and then you check that map. If the map already has an entry, you simply increase that counter; if not; you add a value of 1 for that key. That is more efficient compared to sorting/iterating a list of values!