Randomly generated list

0

I want to generate a list of cars with random characteristics of brand, model, color and year. These values are stored in a car list. The problem is that at the time of doing the loop that calls the gerarCarro() function, which adds random values to the car list, the values from the third car begin to be all equal. p>

using System;
using System.Collections.Generic;
using System.Linq;

public class MainClass
{
  public static List<string> marcaLista = new List<string>();
  public static List<string> modeloLista = new List<string>();
  public static List<string> corLista = new List<string>();

  public static List<string> carro = new List<string> ();

  public static void Main(string[] args)
  {
    marcaLista.Add("Toyota");
    marcaLista.Add("BMW");
    marcaLista.Add("Volkswagen");
    marcaLista.Add("GM");
    marcaLista.Add("Mercedes");

    modeloLista.Add("1.0");
    modeloLista.Add("1.4");
    modeloLista.Add("1.6");
    modeloLista.Add("1.8");
    modeloLista.Add("2.0");

    corLista.Add("Branco");
    corLista.Add("Prata");
    corLista.Add("Preto");
    corLista.Add("Cinza");
    corLista.Add("Vermelho");

    for (int i = 1; i <= 5; i++)
    {
      gerarCarro ();
      foreach (string item in carro)
      {
        Console.WriteLine (item);
      }
      Console.WriteLine ();

      carro.Clear ();
    }

  }

  public static void gerarCarro ()
  {
    int randomizer;

    Random random = new Random ();

    for (int i = 0; i < 4; i++)
    {
      randomizer = random.Next (0, 5);

      switch (i)
      {
        case 0:
          carro.Add (marcaLista[randomizer]);
          break;
        case 1:
          carro.Add (modeloLista[randomizer]);
          break;
        case 2:
          carro.Add (corLista[randomizer]);
          break;
        case 3:
          carro.Add (random.Next (2000, 2018).ToString());
          break;
      }
    }
  }
}
    
asked by anonymous 04.08.2017 / 02:07

2 answers

5

I know it's not exactly the way I wanted it, but it learns how to do it the right way. The main problem is that it was generating a new random seed every time it calls the method, and it ends up being the same. Seed should be generated only once in the application, and making it a class member causes this to occur.

I also organized and modernized the code. It got much leaner. I took what I did not need. I changed the array to a class that is like this in C #. I deleted the loop ( for ) and the select flow ( switch ) that generated elements because it only complicated the code without generating benefit. I made the car be returned so I did not need a member of the class idly.

You can still improve a lot more, but you learn the right thing without having to learn too much.

Make simple codes. It is more readable, but easy to maintain, easier to understand. Get used to C # naming pattern .

using System;
using static System.Console;
using System.Collections.Generic;

public class MainClass {
    public static Random Random = new Random();

    public static List<string> Marcas= new List<string>() { "Toyota", "BMW", "Volkswagen", "GM", "Mercedes" };
    public static List<string> Modelos = new List<string>() { "1.0", "1.4", "1.6", "1.8", "2.0" };
    public static List<string> Cores = new List<string>() { "Branco", "Prata", "Preto", "Cinza", "Vermelho" };

    public static void Main(string[] args) {
        for (int i = 1; i <= 5; i++) {
            var carro = gerarCarro();
            WriteLine(carro.Marca);
            WriteLine(carro.Modelo);
            WriteLine(carro.Cor);
            WriteLine(carro.Ano);
            WriteLine();
        }
    }
    public static Carro gerarCarro() {
        return new Carro() {
            Marca = Marcas[Random.Next(0, 5)],
            Modelo = Modelos[Random.Next(0, 5)],
            Cor = Cores[Random.Next(0, 5)],
            Ano = Random.Next(2000, 2018) };
    }
    public class Carro {
        public string Marca { get; set; }
        public string Modelo { get; set; }
        public string Cor { get; set; }
        public int Ano { get; set; }
    }
}

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .

If you want to avoid repeating the same feature, you should not use random numbers, but rather a Fisher-Yates algorithm . / p>     

04.08.2017 / 02:46
0

Dude, I made a much simpler code to help you with this problem. I still think it's better to improve, especially using LINQ , but since I do not know how to use it, I did it my way:

using System;
using System.Collections.Generic;

namespace CarroSO
{
    class Program
    {
        static List<Carro> carros = new List<Carro>(); //Crio varios array para utilizar melhor os valores
        static string[] marcas = { "Toyota", "BMW", "Volskwagen", "GM", "Mercedes" };
        static string[] modelos = { "1.0", "1.4", "1.6", "1.8", "2.0" };
        static string[] cores = { "Branco", "Prata", "Preto", "Cinza", "Vermelho" };

        static void Main(string[] args)
        {
            int valor;
            Random r = new Random();

            for (int i = 0; i < 5; i++)
            {
                do
                {
                    valor = r.Next(0, 5);
                } while (testarExistencia(modelos[valor])); //Checa se já existe o carro
                carros.Add(new Carro(marcas[valor], modelos[valor], cores[valor])); //Adiciona o carro, caso não exista
            }

            foreach (Carro car in carros) //Passa por todos os carros
                Console.WriteLine($"Marca: {car.marca} - Modelo: {car.modelo} - Cor: {car.cor}"); //Escreve cada um no console
        }

        static bool testarExistencia(string modelo) //Retorna true se já existe e false caso não exista
        {
            foreach (Carro carro in carros)
            {
                if (carro.modelo == modelo)
                {
                    return true;
                }
            }
            return false;
        }
    }

    class Carro
    {
        public string marca { get; set; }
        public string modelo { get; set; }
        public string cor { get; set; }

        public Carro(string marca, string modelo, string cor) //Constructor para criar um objeto do carro
        {
            this.marca = marca;
            this.modelo = modelo;
            this.cor = cor;
        }
    }
}

Notice that I've told you so I can explain a bit of how it works.

    
04.08.2017 / 02:45