Loading...
TStancheva avatar TStancheva 3 Точки

Моля за малко помощ при задача 5. Teamwork projects

Здравейте,

Ще може ли малко помощ по задача по следната задача

Това е кода ми: https://pastebin.com/Ra0h8hpH

Благодаря предварително :)

Условието на задачата е:

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:
    • "Team {teamName} was already created!"
  • 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:
    • "Team {teamName} does not exist!"
  • A member of a team cannot join another team – the following message should be thrown:
    • "Member {user} cannot join team {team Name}!"
  • 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:

Тагове:
0
Fundamentals Module
MartinBG avatar MartinBG 4803 Точки

Ето примерно решение за което използвах Вашето като основа:

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

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());

            var teams = new Dictionary<string, Team>();
            for (var i = 0; i < n; i++)
            {
                var token = Console.ReadLine()
                    .Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var creatorName = token[0];
                var teamName = token[1];

                if (IsExistingTeam(teamName, teams))
                {
                    Console.WriteLine($"Team {teamName} was already created!");
                    continue;
                }

                if (IsTeamCreator(creatorName, teams))
                {
                    Console.WriteLine($"{creatorName} cannot create another team!");
                    continue;
                }

                teams.Add(teamName, new Team(creatorName, teamName));
                Console.WriteLine($"Team {teamName} has been created by {creatorName}!");
            }

            string input;
            while ((input = Console.ReadLine()) != "end of assignment")
            {
                var token = input
                    .Split("->".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var memberName = token[0];
                var teamName = token[1];

                if (!IsExistingTeam(teamName, teams))
                {
                    Console.WriteLine($"Team {teamName} does not exist!");
                    continue;
                }

                if (IsExistingUser(memberName, teams))
                {
                    Console.WriteLine($"Member {memberName} cannot join team {teamName}!");
                    continue;
                }

                teams[teamName].Add(memberName);
            }

            teams.Values
                .Where(team => team.Members.Count > 0)
                .OrderByDescending(team => team.Members.Count)
                .ThenBy(team => team.Name)
                .ToList()
                .ForEach(Console.WriteLine);

            Console.WriteLine("Teams to disband:");
            teams.Values
                .Where(team => team.Members.Count == 0)
                .Select(team => team.Name)
                .OrderBy(name => name)
                .ToList()
                .ForEach(Console.WriteLine);
        }

        private static bool IsTeamCreator(string creatorName, IReadOnlyDictionary<string, Team> teams)
        {
            return teams.Values.Any(team => team.Creator == creatorName);
        }

        private static bool IsExistingTeam(string teamName, IReadOnlyDictionary<string, Team> teams)
        {
            return teams.ContainsKey(teamName);
        }

        private static bool IsExistingUser(string userName, IReadOnlyDictionary<string, Team> teams)
        {
            return teams.Values.Any(team => team.Creator == userName || team.Members.Contains(userName));
        }
    }

    internal class Team
    {
        public string Creator { get; }
        public string Name { get; }
        public List<string> Members { get; } = new List<string>();

        public Team(string creator, string name)
        {
            Creator = creator;
            Name = name;
        }

        public void Add(string user)
        {
            Members.Add(user);
        }

        public override string ToString()
        {
            var output = $"{Name}\n";
            output += $"- {Creator}\n";

            Members.OrderBy(name => name)
                .ToList()
                .ForEach(member => output += $"-- {member}\n");

            return output.Trim();
        }
    }
}

 

0
12/05/2020 16:41:58
TStancheva avatar TStancheva 3 Точки

Благодаря :) Какво прави това ?

    -->          teams.Values
                .Where(team => team.Members.Count == 0)
                .Select(team => team.Name)
                .OrderBy(name => name)
                .ToList()
        -->        .ForEach(Console.WriteLine);
1
12/05/2020 17:06:02
MartinBG avatar MartinBG 4803 Точки

teams.Values:

teams е Dictionary<string, Team>, и съответно teams.Values връща IEnumerable<Teams> - поток от всички тиймове в речника (представете си го като колекция - напр. List<Team>).

 

.ForEach(Console.WriteLine)

Съкратен запис на:

.ForEach(teamName => Console.WriteLine(teamName))

Изпълнява Console.WriteLine за всеки елемент. В случая елементите са имената на тийовете (string).

 

0
MartinBG avatar MartinBG 4803 Точки

@Stancheva

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

Може да е една идея по-сложо от нивото на модула, но е по-близо до това, което се очаква да правите по-нататък в обучението и в работата:

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

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var teamsRegister = new TeamsRegister();

            var n = int.Parse(Console.ReadLine());


            for (var i = 0; i < n; i++)
            {
                var token = Console.ReadLine()
                    .Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var creatorName = token[0];
                var teamName = token[1];

                try
                {
                    teamsRegister.Add(new Team(creatorName, teamName));
                    Console.WriteLine($"Team {teamName} has been created by {creatorName}!");
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            string input;
            while ((input = Console.ReadLine()) != "end of assignment")
            {
                var token = input
                    .Split("->".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var memberName = token[0];
                var teamName = token[1];

                try
                {
                    teamsRegister.AddMemberToTeam(memberName, teamName);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            Console.WriteLine(teamsRegister);
        }
    }

    internal class TeamsRegister
    {
        private readonly Dictionary<string, Team> _teams;

        public TeamsRegister()
        {
            _teams = new Dictionary<string, Team>();
        }

        public override string ToString()
        {
            var sb = new StringBuilder();

            _teams.Values
                .Where(team => team.Members.Count > 0)
                .OrderByDescending(team => team.Members.Count)
                .ThenBy(team => team.Name)
                .ToList()
                .ForEach(team => sb.Append(team).Append("\n"));

            sb.Append("Teams to disband:").Append("\n");

            _teams.Values
                .Where(team => team.Members.Count == 0)
                .Select(team => team.Name)
                .OrderBy(teamName => teamName)
                .ToList()
                .ForEach(teamName => sb.Append(teamName).Append("\n"));

            return sb.ToString();
        }

        private bool IsTeamCreator(string creatorName)
        {
            return _teams.Values.Any(team => team.Creator == creatorName);
        }

        private bool IsExistingTeam(string teamName)
        {
            return _teams.ContainsKey(teamName);
        }

        private bool IsExistingUser(string userName)
        {
            return _teams.Values.Any(team => team.Creator == userName || team.Members.Contains(userName));
        }

        public void Add(Team team)
        {
            if (IsExistingTeam(team.Name))
            {
                throw new ArgumentException($"Team {team.Name} was already created!");
            }

            if (IsTeamCreator(team.Creator))
            {
                throw new ArgumentException($"{team.Creator} cannot create another team!");
            }

            _teams.Add(team.Name, team);
        }

        public void AddMemberToTeam(string memberName, string teamName)
        {
            if (!IsExistingTeam(teamName))
            {
                throw new ArgumentException($"Team {teamName} does not exist!");
            }

            if (IsExistingUser(memberName))
            {
                throw new ArgumentException($"Member {memberName} cannot join team {teamName}!");
            }

            _teams[teamName].Add(memberName);
        }
    }

    internal class Team
    {
        public string Creator { get; }
        public string Name { get; }
        public List<string> Members { get; } = new List<string>();

        public Team(string creator, string name)
        {
            Creator = creator;
            Name = name;
        }

        public void Add(string user)
        {
            Members.Add(user);
        }

        public override string ToString()
        {
            var output = $"{Name}\n";
            output += $"- {Creator}\n";

            Members.OrderBy(name => name)
                .ToList()
                .ForEach(member => output += $"-- {member}\n");

            return output.Trim();
        }
    }
}

 

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