Loading...

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

DragomiraV avatar DragomiraV 0 Точки

06. Courses Малко помощ

Незнам как да го разпиша накрая

Условие:

Write a program that keeps information about courses. Each course has a name and registered students. 

You will be receiving a course name and a student name, until you receive the command "end". Check if such course already exists, and if not, add the course. Register the user into the course. When you receive the command "end", print the courses with their names and total registered users, ordered by the count of registered users in descending order. For each contest print the registered users ordered by name in ascending order. 

Input 

  • Until the "end" command is received, you will be receiving input in the format: "{courseName} : {studentName}". 

  • The product data is always delimited by " : ". 

Output 

  • Print the information about each course in the following the format:  
    "{courseName}: {registeredStudents}" 

  • Print the information about each student, in the following the format: 
    "-- {studentName}" 

Examples 

Input 

Output 

Programming Fundamentals : John Smith 

Programming Fundamentals : Linda Johnson 

JS Core : Will Wilson 

Java Advanced : Harrison White 

end 

Programming Fundamentals: 2 

-- John Smith 

-- Linda Johnson 

JS Core: 1 

-- Will Wilson 

Java Advanced: 1 

-- Harrison White 

Algorithms : Jay Moore 

Programming Basics : Martin Taylor 

Python Fundamentals : John Anderson 

Python Fundamentals : Andrew Robinson 

Algorithms : Bob Jackson 

Python Fundamentals : Clark Lewis 

end 

Python Fundamentals: 3 

-- Andrew Robinson 

-- Clark Lewis 

-- John Anderson 

Algorithms: 2 

-- Bob Jackson 

-- Jay Moore 

Programming Basics: 1 

-- Martin Taylor 

 

Моят код:

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

namespace ConsoleApp11
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, List<string>> students = new Dictionary<string, List<string>>();
            Dictionary<string, int> courses = new Dictionary<string, int>();

            string output;

            while ((output = Console.ReadLine()) != "end")
            {
                string[] inputArray = output.Split(':');
                string kurs = inputArray[0];
                string nameStudent = inputArray[1];
                if (!students.ContainsKey(kurs))
                {
                    students.Add(kurs,new List<string>());
                  
                    courses[kurs] = 0;

                }
                if (!students[kurs].Contains(nameStudent))
                {
                    students[kurs].Add(nameStudent);
                }
                courses[kurs]++;
               

              


            }
            foreach (var kvp in courses)
            {
                Console.WriteLine($"{kvp.Key} : {kvp.Value}");
                foreach (var name in students)
                {
                    Console.WriteLine($"--{(string.Join(" ",name.Value))}");
                }
            }
        }
    }

}

Тагове:
0
Fundamentals Module
nickwork avatar nickwork 657 Точки

Промених ти малко кода...някои разлики съм ги отбелязал...разгледай го и дебъгни

 

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

namespace ConsoleApp11
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, List<string>> students = new Dictionary<string, List<string>>();
            //Dictionary<string, int> courses = new Dictionary<string, int>(); - това е излишно

            string output;

            while ((output = Console.ReadLine()) != "end")
            {
                string[] inputArray = output.Split(" : "); //сплита  е променен
                string kurs = inputArray[0];
                string nameStudent = inputArray[1];
                if (!students.ContainsKey(kurs))
                {
                    students.Add(kurs, new List<string>());

                    students[kurs].Add(nameStudent); // тук е променено
                }
                else
                {
                    students[kurs].Add(nameStudent);
                }
            }
            foreach (var kvp in students.OrderByDescending(x => x.Value.Count()))
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value.Count()}");

                foreach (var name in kvp.Value.OrderBy(x => x))
                {
                    Console.WriteLine($"-- {name}");
                }
            }
        }
    }

}

0
DragomiraV avatar DragomiraV 0 Точки

Благодаря ти !!!!

0
knoteva avatar knoteva 1081 Точки

Здравей,

Не разбирам защо ти е листа "courses", след като в "students" имаш цялата информация(Между другото речникът "students"  е по-логично да се казва "courses"). 

Сортирането и принтиранмето може да стане така:

foreach (var kvp in students.OrderByDescending(x => x.Value.Count)) // Сортираме по броя на регистрираните юзъри
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value.Count()}" +
                                  $"{Environment.NewLine}" +
                                  $"{string.Join(Environment.NewLine, kvp.Value.OrderBy(x => x).Select(x => $"-- {x}"))}");// Сортираме по имената
            }

}

И трябва да сплитваш:  string[] inputArray = output.Split(" : ");

0
DragomiraV avatar DragomiraV 0 Точки

Мерси!!!

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