C# - 7.08.2020 - Final Exam
Здравейте, някой би ли споделил 100 от 100 решения на задачите от финалния изпит? Получавам крайният резултат на първа и втора задача, но не и 100 от 100.
Благодаря предварително!
Здравейте, някой би ли споделил 100 от 100 решения на задачите от финалния изпит? Получавам крайният резултат на първа и втора задача, но не и 100 от 100.
Благодаря предварително!
би трябвало решението на трета задача да изглежда така- с добавяне на проверка за валидност на командите,дори съществува опцията за добавяне на проверка за всички команди извлечени от стринга, който също може да бъде невалиден и програмата да се счупи веднага
без проверка за валидност на а втората команда ми дава 50т.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace regex_demos
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Dictionary<string, List<double>> plants = new Dictionary<string, List<double> >();
for (int i = 0; i < n; i++)
{
string[] input = Console.ReadLine().Split("<->").ToArray();
string plant = input[0];
double rarity = double.Parse(input[1]);
if (!plants.ContainsKey(plant))
{
plants.Add(plant, new List<double>());
plants[plant].Add(rarity);
}
else
{
plants[plant][0] += rarity;//трябва да е само =
}
}
while (true)
{
string input = Console.ReadLine();
if (input == "Exhibition")
{
break;
}
string[] command = input.Split(new char[] { '-', ' ',':' }, StringSplitOptions.RemoveEmptyEntries);
string plant = command[1];
if (!plants.ContainsKey(plant))
{
Console.WriteLine("error");
continue;
}
if (command[0] == "Rate")
{
double rating = double.Parse(command[2]);
plants[plant].Add(rating);
}
else if (command[0] == "Update")
{
double rarity = double.Parse(command[2]);
plants[plant][0] = rarity;
}
else if (command[0] == "Reset")
{
plants[plant].RemoveRange(1, plants[plant].Count - 1);
}
else
{
Console.WriteLine("error");
}
}
foreach (var item in plants)
{
double rarity = item.Value[0];
item.Value.RemoveAt(0);
int count = item.Value.Count;
double sum = item.Value.Sum();
if (sum != 0)
{
sum /= count;
}
item.Value.Clear();
item.Value.Add(rarity);
item.Value.Add(sum);
}
Console.WriteLine("Plants for the exhibition:");
foreach (var item in plants.OrderByDescending(x => x.Value[0]).ThenByDescending(x => x.Value[1]).ToDictionary(x => x.Key,x => x.Value))
{
Console.WriteLine($"- {item.Key}; Rarity: {(int)item.Value[0]}; Rating: {item.Value[1]:f2}");
}
}
}
}
Здравейте! Аз имах особено затруднение с решението на 3та задача от днес. Поствам моето решение, с което получих 50/100. Много се чудих къде бъркам, но не успях да измисля нищо.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Plant_Discovery
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, Dictionary<string, List<double>>> plantsManager =
new Dictionary<string, Dictionary<string, List<double>>>();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
string[] input = Console.ReadLine()
.Split("<->", StringSplitOptions.RemoveEmptyEntries);
var plant = input[0];
var rarity = double.Parse(input[1]);
if (!plantsManager.ContainsKey(plant))
{
plantsManager.Add(plant, new Dictionary<string, List<double>>
{
{ "rarity", new List<double>() { rarity } },
{ "rating", new List<double>() }
});
}
else if (plantsManager.ContainsKey(plant))
{
plantsManager[plant]["rarity"][0] = rarity;
}
}
string command = Console.ReadLine();
while (command != "Exhibition")
{
var tokens = command.Split(": ");
var plantStats = tokens[1].Split(" - ");
var plant = plantStats[0];
if (tokens[0] == "Rate")
{
var rating = double.Parse(plantStats[1]);
plantsManager[plant]["rating"].Add(rating);
}
if (tokens[0] == "Update")
{
var newRarity = double.Parse(plantStats[1]);
plantsManager[plant]["rarity"][0] = newRarity;
}
if (tokens[0] == "Reset")
{
plantsManager[plant]["rating"].Clear();
}
command = Console.ReadLine();
}
var sorted = plantsManager.OrderByDescending(x => x.Value["rarity"][0])
.ThenByDescending(x => x.Value["rating"].Average());
Console.WriteLine("Plants for the exhibition:");
foreach (var plant in sorted)
{
if (plant.Value["rating"].Count > 0)
{
if (plant.Value["rating"].Count == 1)
{
Console.WriteLine($"- {plant.Key}; Rarity: {plant.Value["rarity"][0]:f0}; " +
$"Rating: {plant.Value["rating"][0]:f2}");
}
else
{
var averageRating = plant.Value["rating"].Average();
Console.WriteLine($"- {plant.Key}; Rarity: {plant.Value["rarity"][0]:f0}; " +
$"Rating: {averageRating:f2}");
}
}
else
{
Console.WriteLine($"- {plant.Key}; Rarity: {plant.Value["rarity"][0]:f0}; " +
$"Rating: 0.00");
}
}
}
}
}
Благодаря, Ankoun1, за отделеното време! След като разгледах внимателно решението ти установих, че проблемът при мен не е от незнание как да напиша кода за решението, а в това че не съм разбрала условието и всичките тези термини rarity, rating, кое какво е, са ме объркали тотално какво точно се изисква.
- за отрицателните стойности също може да има проблем още при проверка на следващите команди (rarity),(rating)
double(rarity) ако присвоява отрицателна стойност това би трябвало да е грешка , съществува вероятност корекцията да важи и за double(rating)
ако double(rating) приема отрицателни стойности ,тогава листовете може да се напълнят с отрицателни стойности и проверката за(sum) се променя ако операциите за присвояване са валидни
if (sum != 0) ако са невалидни още преди тази проверка трябва да се направи друга проверка за (sum)
{
sum /= count;
}
ако се иска да се отпечата "грешка" при отрицателна (sum) на всички(rating) от конкретен plants[plant] лист, когато while цикъла е завършил, тогава проверката за (sum) се променя в следващия цикъл за манипулация на данните sum >= 0 за да е валидна
- може да има и още проблеми с неправилен стринг ,който трябва да се сплитне по командите .Тогава трябва да се наблюдава дължината на последващия масив и съдържанието му за валидност ,което е необходимо за правилно последващо деклариране на променливите и следене за "error", затова задачата наистина може да е доста трудна и часовете да се изнижат
To initiate the Dollar General Customer satisfaction tellthebell survey, you’ll get to enter some details from your receipt (that is, the receipt you obtained at your last visit to a Dollar General store). Among the main points to be entered are the time of your visit (as indicated on the receipt), the shop number, and therefore the 15 digit survey code. Of these details are to be found on your Dollar General receipt. Yours is simply to enter them as they’re indicated.
Гениална идея в първия елемнт от Листа да се пази rarity, а останалите стойности да за Rate, браво! :)