0

I try to write a function for generate numbers from 1 to 80 with no-repeat.

the problem is that my generator works incorrectly, because duplicate exists whatever.

public void generator() // сделать по кнопке, но пока что проверка тип на работоспособность 
    {
        Random rand = new Random();

        int[] arr = new int[20];
        int temp = 0;
        foreach (TextBox c in panel1.Controls)
        {
            for (int i = 0; i < 20; i++)
            {
                arr[i] = rand.Next(1, 80);
                temp = arr[i];
                for (int j = 0; j < i; j++)
                {
                    while (arr[i] == arr[j])
                    {
                        arr[i] = rand.Next(1, 80);
                        j = 0;
                        temp = arr[i];
                    }
                    temp = arr[i];
                }
                c.Text = arr[i].ToString();
            }

        }

    }

i tried to use this solution, but i dont understood how to get numbers from List there.

Please, help me

Syncmaxim
  • 47
  • 9

2 Answers2

2

A more consistent way to generate random numbers in small amounts is to make a list from 1 through 80 and then pull the 20 items randomly from the list.

Fisher-Yates shuffle

-1

Another way to avoid duplicated values could be using an "HashSet" object. It allows you to create a list of distinct values. You can use an HashSet object for random numbers, then you can scan these items and fill it wherever you need it. The only problem with HashSet is that it hasn't any index, so we have to transform it into List object.

Below you can find an example:

        var random = new Random();
        HashSet<int> containerSet = new HashSet<int>();
        do
        {
            containerSet.Add(random.Next(1, 80));

        } while (containerSet.Count < 20);

        var position = 0;
        var containerList = containerSet.ToList();
        foreach (TextBox c in panel1.Controls)
        {
            c.Text = containerList[position++];
        }
Fenuska
  • 118
  • 1
  • 9