Loading...
maria_banova avatar maria_banova 1 Точки

09. SoftUni Exam Results C#

Здравейте! Бихте ли ми обяснили защо при първия foreach не ми сортира нищо? 

Условие: 

Problem 9. *SoftUni Exam Results

Judge statistics on the last Programing Fundamentals exam was not working correctly, so you have the task to take all the submissions and analyze them properly. You should collect all the submissions and print the final results and statistics about each language that the participants submitted their solutions in.

You will be receiving lines in the following format: "{username}-{language}-{points}" until you receive "exam finished". You should store each username and his submissions and points.
You can receive a command to ban a user for cheating in the following format: "{username}-banned". In that case, you should remove the user from the contest, but preserve his submissions in the total count of submissions for each language.

After receiving "exam finished" print each of the participants, ordered descending by their max points, then by username, in the following format:

"Results:"

"{username} | {points}"

After that print each language, used in the exam, ordered descending by total submission count and then by language name, in the following format:

"Submissions:"

"{language} – {submissionsCount}"

Input / Constraints

Until you receive "exam finished" you will be receiving participant submissions in the following format: "{username}-{language}-{points}".

You can receive a ban command -> "{username}-banned"

The points of the participant will always be a valid integer in the range [0-100];

Output

  • Print the exam results for each participant, ordered descending by max points and then by username, in the following format:

"Results:"

"{username} | {points}"

  • After that print each language, ordered descending by total submissions and then by language name, in the following format:

"Submissions:"

"{language} – {submissionsCount}"

  • Allowed working time / memory: 100ms / 16MB.

Examples

Input

Output

Comment

Peter-Java-84

George-C#-70

George-C#-84

Sam-C#-94

exam finished

Results:

Sam | 94

George | 84

Peter | 84

Submissions:

C# - 3

Java - 1

We order the participant descending by max points and then by name, printing only the username and the max points.

After that, we print each language along with the count of submissions, ordered descending by submissions count, and then by language name.

Peter-Java-91

George-C#-84

Sam-JavaScript-90

Sam-C#-50

Sam-banned

exam finished

 

Results:

Peter | 91

George | 84

Submissions:

C# - 2

Java - 1

JavaScript - 1

Sam is banned so he is removed from the contest, but his submissions are still preserved in the languages submissions count.

So although there are only 2 participants in the results, there are 4 submissions in total.

 

Линк към кода: https://pastebin.com/KqfwJX7k

Тагове:
0
C# Advanced
Axiomatik avatar Axiomatik 2113 Точки

Ordering does work, however only for each course and not comparing all of the students as a whole group.

;-)

Classical Solution with a third dictionary:

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

namespace softuniExamResults
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> studentGradeList = new Dictionary<string, int>();
            Dictionary<string, int> testCountList = new Dictionary<string, int>();
            Dictionary<string, List<string>> studentTests = new Dictionary<string, List<string>>();

            string command = Console.ReadLine();

            while (command != "exam finished")
            {
                string[] cSplit = command.Split('-');
                if (cSplit.Length == 2)
                {
                    string studentName = cSplit[0];
                    StudentRemover(studentName, studentGradeList);

                }
                else if (cSplit.Length == 3)
                {
                    string studentName = $"{cSplit[0]}-{cSplit[1]}";
                    string testName = cSplit[1];
                    int grade = int.Parse(cSplit[2]);
                    StudentTestAdd(studentName, grade, studentGradeList);
                    TestCounter(testName, testCountList);
                }

                command = Console.ReadLine();
            }

            testCountList = testCountList.OrderByDescending(x => x.Value).ThenBy(x => x.Key).
                ToDictionary(key => key.Key, value => value.Value);
            studentGradeList = studentGradeList.OrderByDescending(x => x.Value).ThenBy(x => x.Key).
                ToDictionary(key => key.Key, value => value.Value);
            StudentPrinter(studentGradeList);
            CounterPrinter(testCountList);
        }




        static void StudentPrinter(Dictionary<string, int> studentGradeList)
        {
            Console.WriteLine("Results:");

            foreach (var student in studentGradeList)
            {
                string[] name = student.Key.Split('-');
                Console.WriteLine($"{name[0]} | {student.Value}");
            }
        }

        static void CounterPrinter(Dictionary<string, int> testCountList)
        {
            Console.WriteLine("Submissions:");

            foreach (var test in testCountList)
            {
                Console.WriteLine($"{test.Key} - {test.Value}");
            }
        }

        static Dictionary<string, int> StudentRemover(string studentName, Dictionary<string, int> studentGradeList)
        {
            foreach (var student in studentGradeList)
            {
                string[] currentName = student.Key.Split('-');

                if (currentName[0] == studentName)
                {
                    studentGradeList.Remove(student.Key);
                }
            }

            return studentGradeList;
        }

        static Dictionary<string, int> TestCounter(string testName, Dictionary<string, int> testCountList)
        {
            if (!testCountList.ContainsKey(testName))
            {
                testCountList.Add(testName, 0);
            }

            testCountList[testName]++;

            return testCountList;
        }

        static Dictionary<string, int> StudentTestAdd(string studentName, int grade, Dictionary<string, int> studentGradeList)
        {
            if (!studentGradeList.ContainsKey(studentName))
            {
                studentGradeList.Add(studentName, grade);
            }
            else
            {
                int currentGrade = studentGradeList[studentName];

                if (grade > currentGrade)
                {
                    studentGradeList[studentName] = grade;
                }
            }

            return studentGradeList;
        }
    }
}

 

Functional Programming variant:

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

class Program
{
    static void Main(string[] args)
    {
        string text = String.Empty;
        Dictionary<string, Dictionary<string, int>> examDict = new Dictionary<string, Dictionary<string, int>>();
        Dictionary<string, int> courses = new Dictionary<string, int>();

        while ((text = Console.ReadLine()) != "exam finished")
        {
            string[] command = text.Split("-");
            string studentName = command[0];

            if (command[1] == "banned")
            {
                foreach (var course in examDict)
                {
                    if (examDict[course.Key].ContainsKey(studentName))
                    {
                        // ExamDict.Remove eliminates by key value, in this case course name and not
                        // studentName, thus target student remains in given course
                        examDict.Remove(studentName);
                    }
                }
                continue;
            }
            else
            {
                string language = command[1];
                int points = int.Parse(command[2]);

                if (!examDict.ContainsKey(language))
                {
                    examDict.Add(language, new Dictionary<string, int>());
                    examDict[language].Add(studentName, points);
                    courses.Add(language, 1);
                }
                else
                {
                    if (!examDict[language].ContainsKey(studentName))
                    {
                        examDict[language].Add(studentName, points);
                    }
                    else
                    {
                        if (points > examDict[language][studentName])
                        {
                            examDict[language][studentName] = points;
                        }
                    }
                    courses[language] += 1;

                }
            }
        }

        // Functional Programming variant, project all students from all courses
        // into a new collection
        var allStudents = examDict
            .Select(course => course.Value)
            .SelectMany(student => student)
            .ToDictionary(key => key.Key, value => value.Value);

        Console.WriteLine($"Results:");

        //foreach (var item in examDict)
        //{
        //    Collection is ordered, but only for each given course and not taking into account
        //    all students together
        //    foreach (var text1 in item.Value.OrderByDescending(x => x.Value).ThenBy(y => y.Key))
        //    {
        //        Console.WriteLine($"{text1.Key} | {text1.Value}");
        //    }
        //}

        foreach (var (name, points) in allStudents.OrderByDescending(x => x.Value).ThenBy(y => y.Key))
        {
            Console.WriteLine($"{name} | {points}");
        }

        Console.WriteLine("Submissions:");

        foreach (var course in courses.OrderByDescending(x => x.Value).ThenBy(y => y.Key))
        {

            Console.WriteLine($"{course.Key} – {course.Value}");
        }
    }
}

 

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