Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

LifeOnMars avatar LifeOnMars 1 Точки

Проблем съ задача Problem 3. Plant Discovery от Programming Fundamentals Final Exam 09.08.2020

Ето това е решението ми досега: https://pastebin.com/Gpz53PkB

Дава ми 50 точки, а половината от тестовете ми гърмят с Runtime Error. Съмнявам се, че е свързано с AverageRating-а или нещо по входа не  като хората, но не мога да разбера.

Тагове:
0
C# Fundamentals
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

Everything is fine, just needed to include an additional validation to check whether given plant exists in collection (see lines 46 - 53):

                Plant currentPlantTest = plants.FirstOrDefault(p => p.Name == plantName);

                if (currentPlantTest == null)
                {
                    Console.WriteLine("error");
                    command = Console.ReadLine();
                    continue;
                }

 

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


namespace PlantDiscovery
{
    class Program
    {
        static void Main(string[] args)
        {

            int n = int.Parse(Console.ReadLine());
            List<Plant> plants = new List<Plant>();

            for (int i = 0; i < n; i++)
            {
                string inputLine = Console.ReadLine();
                string[] inputArgs = inputLine.Split("<->", StringSplitOptions.RemoveEmptyEntries).ToArray();

                string plantName = inputArgs[0];
                int plantRarity = int.Parse(inputArgs[1]);

                if (!plants.Any(x => x.Name == plantName))
                {
                    plants.Add(new Plant(plantName, plantRarity));
                }
                else
                {
                    Plant currentPlant = plants.FirstOrDefault(x => x.Name == plantName);
                    currentPlant.Rarity += plantRarity;
                }
            }

            string command = Console.ReadLine();

            while (command != "Exhibition")
            {

                string[] commandArgs = command.Split(':', StringSplitOptions.RemoveEmptyEntries).ToArray();

                string cmnd = commandArgs[0].Trim();
                string secondCmndPart = commandArgs[1].Trim();
                string[] secondCmndArgs = secondCmndPart.Split('-', StringSplitOptions.RemoveEmptyEntries).ToArray();
                string plantName = secondCmndArgs[0].Trim();

                Plant currentPlantTest = plants.FirstOrDefault(p => p.Name == plantName);

                if (currentPlantTest == null)
                {
                    Console.WriteLine("error");
                    command = Console.ReadLine();
                    continue;
                }

                if (cmnd == "Rate")
                {
                    string srating = secondCmndArgs[1].Trim();
                    int rating = int.Parse(srating);
                    Plant currentPlant = plants.FirstOrDefault(x => x.Name == plantName);
                    currentPlant.ratings.Add(rating);
                }

                else if (cmnd == "Update")
                {
                    string snewRariry = secondCmndArgs[1].Trim();
                    int newRarity = int.Parse(snewRariry);
                    Plant currentPlant = plants.FirstOrDefault(x => x.Name == plantName);
                    currentPlant.Rarity = newRarity;
                }

                else if (cmnd == "Reset")
                {
                    Plant currentPlant = plants.FirstOrDefault(x => x.Name == plantName);
                    currentPlant.ratings.Clear();
                }
                else
                {
                    Console.WriteLine("error");
                }

                command = Console.ReadLine();
            }


            Console.WriteLine("Plants for the exhibition:");

            foreach (Plant plant in plants.OrderByDescending(x => x.Rarity).ThenByDescending(x => x.AverageRating))
            {
                Console.WriteLine(plant);
            }
        }




        class Plant
        {

            public string Name { get; set; }

            public int Rarity { get; set; }

            public double AverageRating
            {
                get
                {
                    if (ratings.Count == 0)
                    {
                        return 0.00;
                    }
                    else if (ratings.Count == 1)
                    {
                        return ratings[0];
                    }
                    else
                    {
                        return ratings.Sum() / ratings.Count;
                    }
                }

                set { }
            }


            public List<double> ratings = new List<double>();

            public Plant(string _name, int _rarity)
            {
                Name = _name;
                Rarity = _rarity;
            }

            public override string ToString()
            {
                return $"- {Name}; Rarity: {Rarity}; Rating: {AverageRating:f2}";
            }
        }
    }
}

 

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.