How to draw words from an array without repeating them?

Asked

Viewed 686 times

1

I am doing a college project where I need to simulate the lottery, so I have an array with the name of 20 teams and I need to draw 10 teams but without repeating any and present these teams in a Listbox, but I am not succeeding, could give me suggestions on how to create this method of drawing?

And if possible, some way to add the values of a Checkbox in a array to make the comparison with the teams drawn.

Man array:

public String[] times =
          {
                "Corinthians"
                ,"Palmeiras"
                ,"Santos"
                ,"Grêmio"
                ,"Cruzeiro"
                ,"Botafogo"
                ,"Flamengo"
                ,"Vasco da Gama"
                ,"Atlético-PR"
                ,"Atlético"
                ,"São Paulo"
                ,"Chapecoense"
                ,"Bahia"
                ,"Fluminense"
                ,"Sport Recife"
                ,"Coritiba"
                ,"Ponte Preta"
                ,"Avaí"
                ,"EC Vitória"
             };
  • As the original question shows, do not use Random repeatedly, use it only to shuffle. The answer here is quadratic and has poor performance.

1 answer

2


First declare a Random

Random rnd = new Random();

Make the Random take a value in the middle of the array by the generated Random in the index

int r = rnd.Next(times.Length);

Now you can get your team:

var timesorteado = ((string)times[r]);

Then generate a list and add.. and Filtre to not add duplicate

I made a simple example in a console application, but it can be improved.. but just to give you idea of the logic, do not forget the using System.Linq; and System.Collections.Generic;

private static void Main(string[] args)
{
    String[] times =
    {
        "Corinthians", "Palmeiras", "Santos", "Grêmio", "Cruzeiro", "Botafogo", "Flamengo", "Vasco da Gama",
        "Atlético-PR", "Atlético", "São Paulo", "Chapecoense", "Bahia", "Fluminense", "Sport Recife",
        "Coritiba", "Ponte Preta", "Avaí", "EC Vitória"
    };

    var lstTimesSorteados = new List<string>();

    for (var i = 0; i < 10; i++)
    {
        var timesorteado = Sorteio(times);

        if (!lstTimesSorteados.Any(x => x.Contains(timesorteado)))
        {
            lstTimesSorteados.Add(timesorteado);
        }
        else
        {
            i--;
        }
    }
}

private static string Sorteio(string[] times)
{
    var rnd = new Random();

    var r = rnd.Next(times.Length);
    return ((string)times[r]);
}

Then it’s simple, just compare your checkbox with the TimesSorted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.