Loading...
bparvanova avatar bparvanova 7 Точки

03. MOBA Challenger C#

Здравейте,

 

Бихте ли ми помогнали със задачата.

В Judge получавам 70/100 като на три теста ми излиза Runtime error.

 

Ето го кода: https://pastebin.com/BTF2iWaK

Това е условието:

1.MOBA Challenger

Pesho is a pro MOBA player, he is struggling to become а master of the Challenger tier. So he watches carefully the statistics in the tier.

You will receive several input lines in one of the following formats:

"{player} -> {position} -> {skill}"

"{player} vs {player}"

The player and position are strings, the given skill will be an integer number. You need to keep track of every player.

When you receive a player and his position and skill, add him to the player pool, if he isn`t present, else add his position and skill or update his skill, only if the current position skill is lower than the new value.

If you receive "{player} vs {player}" and both players exist in the tier, they duel with the following rules:

Compare their positions, if they got at least one in common, the player with better total skill points wins and the other is demoted from the tier -> remove him. If they have same total skill points, the duel is tie and they both continue in the Season.

If they don`t have positions in common, the duel isn`t happening and both continue in the Season.

You should end your program when you receive the command "Season end". At that point you should print the players, ordered by total skill in desecending order, then ordered by player name in ascending order. Foreach player print their position and skill, ordered desecending by skill, then ordered by position name in ascending order.

Input / Constraints

  • The input comes in the form of commands in one of the formats specified above.
  • Player and position will always be one word string, containing no whitespaces.
  • Skill will be an integer in the range [0, 1000].
  • There will be no invalid input lines.
  • The programm ends when you receive the command "Season end".

Output

  • The output format for each player is:

"{player}: {totalSkill} skill"

"- {position} <::> {skill}"

Examples

Input

Output

Comments

Peter -> Adc -> 400

George -> Jungle -> 300

Sam -> Mid -> 200

Sam -> Support -> 250

Season end

Sam: 450 skill

- Support <::> 250

- Mid <::> 200

Peter: 400 skill

- Adc <::> 400

George: 300 skill

- Jungle <::> 300

We order the players by total skill points descending, then by name. We print every position along its skill ordered descending by skill, then by position name.

Peter -> Adc -> 400

Bush -> Tank -> 150

Faker -> Mid -> 200

Faker -> Support -> 250

Faker -> Tank -> 250

Peter vs Faker

Faker vs Bush

Faker vs Hide

Season end

Faker: 700 skill

- Support <::> 250

- Tank <::> 250

- Mid <::> 200

Peter: 400 skill

- Adc <::> 400

Faker and Peter don`t have common position, so the duel isn`t valid.

Faker wins vs Bush /common position: "Tank". Bush is demoted.

Hide doesn`t exist so the duel isn`t valid.

We print every player left in the tier.

Тагове:
0
Fundamentals Module
Axiomatik avatar Axiomatik 2422 Точки

Main-problems probably in " vs " command and final output printing (see code).

Also, adding a more "advanced" solution demonstrated by SoftUni instructors that works with class object. Super helpful if you look through it.

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
namespace _3._MOBA_Challenger
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Dictionary<string, int>>
                trackPlayers = new Dictionary<string, Dictionary<string, int>>();
            Dictionary<string, int> playerSkills = new Dictionary<string, int>();
 
            while (true)
            {
                {
                    string line = Console.ReadLine();
 
                    if (line == "Season end")
                    {
                        break;
                    }
 
                    if (line.Contains(" -> "))
                    {
                        string[] parts = line.Split(" -> ");
                        string player = parts[0];
                        string position = parts[1];
                        int skills = int.Parse(parts[2]);
 
                        if (!trackPlayers.ContainsKey(player))
                        {
                            trackPlayers.Add(player, new Dictionary<string, int>());
                            trackPlayers[player].Add(position, skills);
                            playerSkills.Add(player, skills);
                        }
                        else
                        {
                            {
                                if (!trackPlayers[player].ContainsKey(position))
                                {
                                    trackPlayers[player].Add(position, skills);
                                    playerSkills[player] += skills;
                                }
                                else
                                {
                                    int oldSkill = trackPlayers[player][position];
 
                                    if (skills > oldSkill)
                                    {
                                        trackPlayers[player][position] = skills;
                                        int diff = skills - oldSkill;
                                        playerSkills[player] += diff;
                                    }
                                }
                            }
                        }
                    }
 
                    if (line.Contains(" vs "))
                    {
                        string[] playersDuel = line.Split(" vs ");
                        string player1 = playersDuel[0];
                        string player2 = playersDuel[1];
 
                        if (trackPlayers.ContainsKey(player1) && trackPlayers.ContainsKey(player2))
                        {
                            string playerToRemove = "";
                            foreach (var role in trackPlayers[player1]) // better skillPlayer1
                            {
                                foreach (var pos in trackPlayers[player2]) // better skillPlayer2
                                {
                                    if (role.Key == pos.Key)
                                    {
                                        if (trackPlayers[player1].Values.Sum() > trackPlayers[player2].Values.Sum())
                                        {
                                            playerToRemove = player2;
                                        }
                                        else if (trackPlayers[player1].Values.Sum() <
                                                 trackPlayers[player2].Values.Sum())
                                        {
                                            playerToRemove = player1;
                                        }
                                    }
                                }
 
                                trackPlayers.Remove(playerToRemove);
                                // break;
                                // add break after removing from collection,
                                // otherwise will cause exception when modifying collection
                                // during foreach 
                            }
                        }
                    }
                }
            }
            // At that point you should print the players, ordered by total skill in desecending order, 
            // then ordered by player name in ascending order.  (missing here ??)
            // foreach (var player in playerSkills.OrderByDescending(x => x.Value))
            foreach (var player in playerSkills.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
            {
                string name = player.Key;
                int totalSkills = player.Value;
                Console.WriteLine($"{name}: {totalSkills} skill");
 
                // Foreach player print their position and skill, ordered desecending by skill, 
                // then ordered by position name in ascending order (missing here ??)
                // foreach (var roleSkill in trackPlayers[name].OrderByDescending(x => x.Value))
                foreach (var roleSkill in trackPlayers[name].OrderByDescending(x => x.Value).ThenBy(x => x.Key))
                {
                    string role = roleSkill.Key;
                    int skill = roleSkill.Value;
                    Console.WriteLine($"- {role} <::> {skill}");
                }
            }
        }
    }
}

 

SoftUni-Instructors Demo:

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

namespace MOBAChallenger_withClass
{
    public class Program
    {
        private static void Main()
        {
            var dictNamePlayer = new Dictionary<string, Player>();
            string command;
            while ((command = Console.ReadLine()) != "Season end")
            {
                if (!command.Contains("vs"))
                {
                    var commandArray = command.Split(" -> ");
                    var playerName = commandArray[0];
                    var position = commandArray[1];
                    var skill = int.Parse(commandArray[2]);

                    if (!dictNamePlayer.ContainsKey(playerName))
                    {
                        var newPlayer = new Player(playerName);
                        dictNamePlayer.Add(playerName, newPlayer);
                    }

                    dictNamePlayer[playerName].AddOrUpdatePosition(position, skill);
                }
                else
                {
                    var commandArray = command.Split(' ');
                    var firstPlayer = commandArray[0];
                    var secondPlayer = commandArray[2];

                    if (!dictNamePlayer.ContainsKey(firstPlayer) || !dictNamePlayer.ContainsKey(secondPlayer))
                    {
                        continue;
                    }

                    var playerOne = dictNamePlayer[firstPlayer];
                    var playerTwo = dictNamePlayer[secondPlayer];

                    if (playerOne.GetTotalSkillPoints() == playerTwo.GetTotalSkillPoints())
                    {
                        continue;
                    }

                    var duelsCount = playerOne.GetPositions()
                        .Intersect(playerTwo.GetPositions())
                        .Count();

                    if (duelsCount <= 0)
                    {
                        continue;
                    }

                    dictNamePlayer.Remove(playerOne.GetTotalSkillPoints() > playerTwo.GetTotalSkillPoints()
                        ? playerTwo.Name
                        : playerOne.Name);
                }
            }

            PrintResult(dictNamePlayer.Values.ToList());
        }

        private static void PrintResult(IEnumerable<Player> players)
        {
            foreach (var player in players
                .OrderByDescending(player => player.GetTotalSkillPoints())
                .ThenBy(player => player.Name))
            {
                Console.WriteLine($"{player.Name}: {player.GetTotalSkillPoints()} skill");

                foreach (var (position, skill) in player
                    .GetPositionsAndSkillsDictionary()
                    .OrderByDescending(x => x.Value)
                    .ThenBy(x => x.Key))
                {
                    Console.WriteLine($"- {position} <::> {skill}");
                }
            }
        }

        private class Player
        {
            public string Name { get; }

            private readonly Dictionary<string, int> _dictPositionSkill;

            public Player(string name)
            {
                Name = name;
                _dictPositionSkill = new Dictionary<string, int>();
            }

            public void AddOrUpdatePosition(string position, int skill)
            {
                if (!_dictPositionSkill.ContainsKey(position))
                {
                    _dictPositionSkill.Add(position, skill);
                }
                else if (_dictPositionSkill[position] < skill)
                {
                    _dictPositionSkill[position] = skill;
                }
            }

            public IEnumerable<string> GetPositions()
            {
                return _dictPositionSkill.Keys;
            }

            public ImmutableDictionary<string, int> GetPositionsAndSkillsDictionary()
            {
                return _dictPositionSkill.ToImmutableDictionary();
            }

            public int GetTotalSkillPoints()
            {
                return _dictPositionSkill.Values.Sum();
            }
        }
    }
}

 

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