Loading...
AntonioSimeonov avatar AntonioSimeonov 0 Точки

Teamwork Projects 83/100 [C#]

Моля, ако някой има време, да ми прегледа решението и да ми каже къде бъркам, защото не зацепвам. Мерси!

 

5. Teamwork Projects

It's time for the teamwork projects and you are responsible for gathering the teams. First you will receive an integer - the count of the teams you will have to register. You will be given a user and a team, separated with “-”.  The user is the creator of the team. For every newly created team you should print a message:

"Team {teamName} has been created by {user}!".

Next, you will receive an user with a team, separated with "->", which means that the user wants to join that team. Upon receiving the command: “end of assignment”, you should print every team, ordered by the count of its members (descending) and then by name (ascending). For each team, you have to print its members sorted by name (ascending). However, there are several rules:

  • If an user tries to create a team more than once, a message should be displayed:
    •  
  • A creator of a team cannot create another team – the following message should be thrown:
    • {user} cannot create another team!"
  • If an user tries to join a non-existent team, a message should be displayed:
    •  
  • A member of a team cannot join another team – the following message should be thrown:
    •  
  • In the end, teams with zero members (with only a creator) should disband and you have to print them ordered by name in ascending order.
  • Every valid team should be printed ordered by name (ascending) in the following format:

"{teamName}:

- {creator}

-- {member}…"

Examples

Input

Output

Comments

2

Didi-PowerPuffsCoders

Toni-Toni is the best

Petq->PowerPuffsCoders

Toni->Toni is the best

end of assignment

Team PowerPuffsCoders has been created by Didi!

Team Toni is the best has been created by Toni!

Member Toni cannot join team Toni is the best!

PowerPuffsCoders

- Didi

-- Petq

Teams to disband:

Toni is the best

Toni created a team, which he attempted to join later and this action resulted in throwing a certain message. Since nobody else tried to join his team, the team had to disband.

3

Tatyana-CloneClub

Helena-CloneClub

Trifon-AiNaBira

Pesho->aiNaBira

Pesho->AiNaBira

Tatyana->Leda

PeshO->AiNaBira

Cossima->CloneClub

end of assignment

Team CloneClub has been created by Tatyana!

Team CloneClub was already created!

Team AiNaBira has been created by Trifon!

Team aiNaBira does not exist!

Team Leda does not exist!

AiNaBira

- Trifon

-- Pesho

-- PeshO

CloneClub

- Tatyana

-- Cossima

Teams to disband:

Note that when a user joins a team, you should first check if the team exists and then check if the user is already in a team:

 

Tatyana has created CloneClub, then she tried to join a non-existent team and the concrete message was displayed.

Решението: 

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

namespace ObjectsAndClassesExercise
{
    class Program

    {
        static void Main(string[] args)
        {
            int count = int.Parse(Console.ReadLine());
            List<Team> allTeams = new List<Team>();

            for (int i = 0; i < count; i++)
            {
                string[] teamTokens = Console.ReadLine().Split("-");
                string creator = teamTokens[0];
                string name = teamTokens[1];

                Team existingTeam = allTeams.Find(t => t.TeamName == name);
                Team existingTeamCreator = allTeams.Find(t => t.Creator == creator);

                if (existingTeam != null)
                {
                    Console.WriteLine($"Team {name} was already created!");
                    continue;
                }

                if (existingTeamCreator != null)
                {
                    Console.WriteLine($"{creator} cannot create another team!");
                    continue;
                }


                Team myTeam = new Team(teamTokens[0], teamTokens[1]);
                allTeams.Add(myTeam);
                Console.WriteLine($"Team {myTeam.TeamName} has been created by {myTeam.Creator}!");
            }

            string line = Console.ReadLine();

            while (line != "end of assignment")
            {
                string[] tokens = line.Split("->");
                string member = tokens[0];
                string name = tokens[1];

                Team existingTeam = allTeams.Find(t => t.TeamName == name);
                Team existingTeamMember = allTeams.Find(t => t.Members.Contains(member) || t.Creator == member);

                if (existingTeam == null)
                {
                    Console.WriteLine($"Team {name} does not exist!");
                    line = Console.ReadLine();
                    continue;
                }

                if (existingTeamMember != null)
                {
                    Console.WriteLine($"Member {member} cannot join team {name}!");
                    line = Console.ReadLine();
                    continue;
                }

                existingTeam.Members.Add(member);
                line = Console.ReadLine();
            }

            List<string> allDisbandedTeams = allTeams
                .Where(a => a.Members.Count == 0).
                OrderBy(a => a.TeamName).
                Select(a => a.TeamName). // Защото не искаме списък от Team, а списък от стрингове
                ToList();
            allTeams.RemoveAll(t => t.Members.Count == 0);
            List<Team> sortedTeams = allTeams
                .OrderByDescending(t => t.Members.Count)
                .ThenBy(t => t.TeamName)
                .ToList();
            //.Foreach(t => Console.WriteLine(t)); ;


            foreach (Team team in sortedTeams)
            {
                Console.WriteLine(team.ToString());
            }
            Console.WriteLine("Teams to disband:");
            foreach (string team in allDisbandedTeams)
            {
                Console.WriteLine(team);
            }
        }
    }
}

 


class Team
{
    public Team(string creator, string team)
    {
        this.Creator = creator;
        this.TeamName = team;

        this.Members = new List<string>();
    }


    public string Creator { get; set; }
    public string TeamName { get; set; }
    public List<string> Members { get; set; }   

    public override string ToString()
    {
        List<string> sortedMembers = this.Members.OrderBy(t => t).ToList();
        string output = $"{this.TeamName}\n";
        output += $"- {this.Creator}\n";

        for (int i = 0; i < sortedMembers.Count; i++)
        {
            output += $"-- {this.Members[i]}\n";
        }

        return output.Trim();
    }
}

 

Тагове:
0
Fundamentals Module
VladimirPavlov1 avatar VladimirPavlov1 4 Точки

Здравей,

Ако имаш 83/100, най-вероятно ти липсва сортиране на имената в даден отбор. Освен имената на отборите, трябва да се сортират имената и на играчите в тях. Ей такова парче ти липсва(на Java е, но мисля, че ще се ориентираш): 

for (int i = 0; i < listProperTeams.size(); i++) {
	listProperTeams.get(i).teamPlayers.sort(Comparator.comparing(Player::getName));
}

 

 

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