1
resposta

[Projeto] Faça como eu fiz - Aula Listas e Loops em C#

List<int> listIntegerNumber;

string listStringReturn = "";

const int QUANTITY_ELEMENTS = 10;

Main();
bool ValidarRepeticaoNumeroLista(int value)
{
    if (listIntegerNumber.Contains(value))
    {
        return true;
    }
    else
    {
        return false;
    }
}

int GerarNumeroAleatorio()
{
    int generatedNumber = 0;

    Random random = new Random();

    do
    {
        generatedNumber = random.Next(1, 1001);
    }
    while (ValidarRepeticaoNumeroLista(generatedNumber));

    return generatedNumber;
}

void PreencherListaAleatoriamente()
{
    for (int i = 0; i < QUANTITY_ELEMENTS; i++)
    {
        listIntegerNumber.Add(GerarNumeroAleatorio());
    }
}

void InserirListaString(string value)
{
    if (listStringReturn != "")
    {
        listStringReturn += ", " + value;
    }
    else
    { 
        listStringReturn += value;
    }
}

void MontarListaFor()
{

    for (int i = 0; i < listIntegerNumber.Count; i++)
    {
        if (listIntegerNumber[i]%2 == 0)
        {
            InserirListaString(listIntegerNumber[i].ToString());
        }
    }

    ExibirLista("\n\nExibição dos valores pares da lista utilizando FOR: ");

    listStringReturn = "";
}

void MontarListaForeach()
{

    int count = listIntegerNumber.Count;

    foreach (int item in listIntegerNumber)
    {
        count++;

        if (item%2 == 0)
        {
            InserirListaString(item.ToString());
        }
    }
    ExibirLista("\n\nExibição dos valores pares da lista utilizando FOREACH: ");

    listStringReturn = "";
}

void MontarListaCompleta()
{

    foreach (int item in listIntegerNumber)
    {
        InserirListaString(item.ToString());
    }

    ExibirLista("\n\nLista Gerada: ");

    listStringReturn = "";
}

void ExibirLista(string title)
{
    Console.WriteLine(title + listStringReturn);
}

void Main()
{
    listIntegerNumber = new List<int>();

    PreencherListaAleatoriamente();

    MontarListaCompleta();

    MontarListaFor();

    MontarListaForeach();
}

Teste do funcionamento do código: Insira aqui a descrição dessa imagem para ajudar na acessibilidade

1 resposta

Olá, Gustavo. Tudo bem?

Muito obrigado por compartilhar o seu código aqui com a gente. Parabéns pelo trabalho. Continue com essa dedicação.

Ótimo como você estruturou suas funções para gerar e manipular a lista de números aleatórios. A separação das responsabilidades torna o código mais organizado. Mas repare que, na função MontarListaForeach, você está incrementando a variável count, mas ela não está sendo usada depois.

Um detalhe interessante: ao inicializar um Random dentro da função GerarNumeroAleatorio, pode haver números repetidos se chamado rapidamente em sequência. Para evitar isso, você pode criar uma instância de Random fora da função e reutilizá-la:


Random random = new Random();

int GerarNumeroAleatorio()
{
    int generatedNumber;
    do
    {
        generatedNumber = random.Next(1, 1001);
    } while (listIntegerNumber.Contains(generatedNumber));

    return generatedNumber;
}

Isso melhora a distribuição dos números gerados.

Conte com o apoio do Fórum. Abraços e bons estudos.