Професионална програма
Loading...
antonfotev avatar antonfotev 3 Точки

Objects and classes Exercise 6. Vehicle catalogue

Здравейте. Дава ми 33 точки.
Условието:
Objects and classes Exercise 6. Vehicle catalogue
You have to make a catalogue for vehicles. You will receive two types of vehicle – car or truck.
Until you receive the command “End” you will receive lines of input in the format:
{typeOfVehicle} {model} {color} {horsepower}
After the “End” command, you will start receiving models of vehicles. Print for every received vehicle
its data in the format:
Type: {typeOfVehicle}

Model: {modelOfVehicle}
Color: {colorOfVehicle}
Horsepower: {horsepowerOfVehicle}
When you receive the command “Close the Catalogue”, stop receiving input and print the average
horsepower for the cars and for the trucks in the format:
{typeOfVehicles} have average horsepower of {averageHorsepower}.
The average horsepower is calculated by dividing the sum of horsepower for all vehicles of the type
by the total count of vehicles from the same type.
Format the answer to the 2 nd decimal point.
Constraints
 The type of vehicle will always be car or truck.
 You will not receive the same model twice.
 The received horsepower will be integer in the interval [1…1000]
 You will receive at most 50 vehicles.
 Single whitespace will be used for separator.

КОДЪТ МИ Е
 

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

public class Vehicle
{
    public Vehicle(){}
    public Vehicle(string type, string model, string color, int horsepower)
    {
      this.Type = type;
      this.Model= model;
      this.Color = color;
      this.Horsepower = horsepower;    
    }
    
 public string Type {get; set;}
 public string Model {get; set;}
 public string Color {get; set;}
 public int Horsepower {get; set;}
}
                    
public class Program
{
    public static void Main()
    {
      var orderVehiclkles = new List<Vehicle>();
        
        string inputPrim = null;
        
        while ((inputPrim = Console.ReadLine()) != "End")
        {
            string[] input = inputPrim
                .Split();

            orderVehiclkles.Add(new Vehicle(input[0], input[1], input[2], int.Parse(input[3])));        
        } // end while
        
        while ((inputPrim = Console.ReadLine()) != "Close the Catalogue")
        {        
          foreach (var kvp in orderVehiclkles)
          {
             if(kvp.Model == inputPrim)
             {
                var currnetVehicle = new Vehicle(kvp.Type, kvp.Model, kvp.Color, kvp.Horsepower);
                GetPrintTisVehickle(currnetVehicle);
                break;
             }
          } // first foreach
        } // end while
        
        decimal CarsHorsepower = 0;
        decimal TrucksHorsepower = 0;
        
         foreach (var kvp in orderVehiclkles)
          {
            if(kvp.Type == "car") 
            {
             CarsHorsepower += kvp.Horsepower;  
            }
            else
            {
             TrucksHorsepower += kvp.Horsepower;  
            }
            
          } // first foreach
        int n = orderVehiclkles.Where(s => s.Type == "car").Count();
        int x = orderVehiclkles.Where(s => s.Type == "truck").Count();
        if(n > 0)
        {
         CarsHorsepower = CarsHorsepower / n;    
         Console.WriteLine("Cars have average horsepower of: {0:0.00}.", CarsHorsepower);
        }
        else
        {
         Console.WriteLine("Cars have average horsepower of: 0.00");
        }
        
        if (x > 0)
        {
         TrucksHorsepower = TrucksHorsepower / x;
         Console.WriteLine("Trucks have average horsepower of: {0:0.00}.", TrucksHorsepower);
        }
        else
        {
         Console.WriteLine("Trucks have average horsepower of: 0.00");
        } // end dable if-else
        
    }
    
    public static void GetPrintTisVehickle(Vehicle currnetVehicle)
    {
        if(currnetVehicle.Type == "car")
        {
         Console.WriteLine("Type: Car"); 
        }
        else
        {
         Console.WriteLine("Type: Truck");     
        }
        
        Console.WriteLine("Model: {0}", currnetVehicle.Model); 
        Console.WriteLine("Color: {0}", currnetVehicle.Color);                  
        Console.WriteLine("Horsepower: {0}", currnetVehicle.Horsepower); 
    }                
}

// truck Man red 200
// truck Mercedes blue 300
// car Ford green 120
// car Ferrari red 550
// car Lamborghini orange 570
// End
// Ferrari
// Ford
// Man
// Close the Catalogue

// Type: Car
// Model: Ferrari
// Color: red
// Horsepower: 550
// Type: Car
// Model: Ford
// Color: green
// Horsepower: 120
// Type: Truck
// Model: Man
// Color: red
// Horsepower: 200
// Cars have average horsepower of: 413.33.
// Trucks have average horsepower of: 250.00.

Тагове:
0
Teamwork and Personal Skills
AntonNNikolov avatar AntonNNikolov 1 Точки

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

namespace SixthTask
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> input = Console.ReadLine().Split(" ").ToList();

            List<VehicleCatalouge> wholeCatalouge = new List<VehicleCatalouge>();

            while(input[0] != "End")
            {
                
               if (input[0] == "truck" || input[0] == "car")
                {
                    if (wholeCatalouge.Count > 50)
                    {
                        break;
                    }

                    bool isNotRepeated = false;

                    if (wholeCatalouge.Count == 0)
                    {
                        isNotRepeated = true;
                    }
                    for (int i = 0; i < wholeCatalouge.Count; i++)
                    {
                        if (wholeCatalouge[i].Model == input[1])
                        {
                            isNotRepeated = false;
                        }else
                        {
                            isNotRepeated = true;
                            break;
                        }
                    }
                    if (isNotRepeated)
                    {
                        int inputInt = int.Parse(input[3]);
                        if (inputInt > 0 && inputInt <= 1000)
                        {
                            VehicleCatalouge currentItems = new VehicleCatalouge(input[0], input[1], input[2], inputInt);
                            wholeCatalouge.Add(currentItems);
                        }
                    }
                    
                    
                }
                input = Console.ReadLine().Split(" ").ToList();
            }

            string secondInput = Console.ReadLine();

            while(secondInput != "Close the Catalogue")
            {
                for (int i = 0; i < wholeCatalouge.Count; i++)
                {
                    if(wholeCatalouge[i].Model == secondInput)
                    {
                        Console.WriteLine(wholeCatalouge[i].ToString());
                    }
                }

                secondInput = Console.ReadLine();
            }

            int totalCarHorsePower = 0;
            double totalCars = 0;
            int totalTruckHorsePower = 0;
            double totalTrucks = 0;
            for (int i = 0; i < wholeCatalouge.Count; i++)
            {
                if (wholeCatalouge[i].TypeOfVehicle == "car")
                {
                    totalCarHorsePower += wholeCatalouge[i].HorsePower;
                    totalCars++;
                }else if (wholeCatalouge[i].TypeOfVehicle == "truck")
                {
                    totalTruckHorsePower += wholeCatalouge[i].HorsePower;
                    totalTrucks++;
                }
            }

            double averageCarHorsePower = totalCarHorsePower / totalCars;
            double averageTruckHorsePower = totalTruckHorsePower / totalTrucks;

            Console.WriteLine($"Cars have average horsepower of: {averageCarHorsePower:f2}.");
            Console.WriteLine($"Trucks have average horsepower of: {averageTruckHorsePower:f2}.");
        }
    }

    class VehicleCatalouge
    {
        public VehicleCatalouge (string typeOfVehicle, string model, string color, int horsePower)
        {
            TypeOfVehicle = typeOfVehicle;
            Model = model;
            Color = color;
            HorsePower = horsePower;
        }

       public string TypeOfVehicle { get; set; }
       public string Model { get; set; }
       public string Color { get; set; }
       public int HorsePower { get; set; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append($"Type: {char.ToUpper(TypeOfVehicle[0]) + TypeOfVehicle.Substring(1)}");
            sb.Append(Environment.NewLine);
            sb.Append($"Model: {Model}");
            sb.Append(Environment.NewLine);
            sb.Append($"Color: {Color}");
            sb.Append(Environment.NewLine);
            sb.Append($"Horsepower: {HorsePower}");
            return sb.ToString();

        }

    }
    
}


И аз получавам 33/100, аз съм сложил всички constraints Даже. :) Дано нямаерим решение. :D

0
antonfotev avatar antonfotev 3 Точки

Мисля, че при теб грешката е ето тук:

                    bool isNotRepeated = false;


                    for (int i = 0; i < wholeCatalouge.Count; i++)
                    {
                        if (wholeCatalouge[i].Model == input[1])
                        {
                            isNotRepeated = false;
                        }else
                        {
                            isNotRepeated = true;
                            break;
                        }
                    }

Обяснявам:
Да кажем, че съвпадението ти ще е на клетка с №1.
Проверката ти тръгва от клетка №0, установява липса на съвпадение /съвпадението ще е при клекта №1/и влиза в елс-а.
Там задава стойност на булевата ти функия - true и брейква цикъла.

По добре обърни логиката на проверката ето така:

bool isNotRepeated = true;

for (int i = 0; i < wholeCatalouge.Count; i++)
                    {
                        if (wholeCatalouge[i].Model == input[1])
                        {
                            isNotRepeated = false;
                            break;
                        }
                   } // end for

По този начин, ако изцикли целия лист без съвпадение, булевата ще остане с дефолтната си стойност. / ако установяваш "лъжа", дефултната стойност трябва да е истина/ 

Ако намери съвпадение, ще промени булевата на false и ще брейкне цикъла на проверката.

П.П. Надявам се, че съм ти бил полезен.

С уважение и бъди здрав: Черно Слънце

 

0