Loading...

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

Elena123456 avatar Elena123456 235 Точки

09. ForceBook (Associative Arrays - Exercise)- 90/100

The problem is in Test #8 (Incorrect answer). Can somebody please help me to correct my code, because I was not abble to.

https://softuni.bg/trainings/resources/officedocument/49587/associative-arrays-exercise-csharp-fundamentals-may-2020/2830

https://judge.softuni.bg/Contests/Compete/Index/1213#8

https://pastebin.com/EfGVcGrd

Тагове:
0
C# Fundamentals 31/10/2020 18:09:27
Axiomatik avatar Axiomatik 2422 Точки

Yeah, I had the same error - the trick is that when a current side doesn't exist and a new group is created you still need to check whether the current member does not exist in the other groups and make the member change the group if present in the other groups.

Best,

I think this should do the trick:

else if (input.Contains('>'))
            {

                string[] inputArray = input.Split(" -> ").ToArray();
                string forceUser = inputArray[0];
                string forceSide = inputArray[1];

                if (dictOfAllMembers.ContainsKey(forceSide) == true)
                {
                    bool haveChange = false;
                    List<string> listOfCurrentUsers = dictOfAllMembers[forceSide];
                    if (listOfCurrentUsers.Contains(forceUser) == false)//if user doesn't contains in currentList
                    {
                        foreach (var item in dictOfAllMembers)
                        {
                            string currentSide = string.Empty;
                            if (item.Value.Contains(forceUser))//if user contains in dictionary where is
                            {
                                currentSide = item.Key;
                                dictOfAllMembers[currentSide].Remove(forceUser);//can remove the user
                                dictOfAllMembers[forceSide].Add(forceUser);
                                Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                                haveChange = true;
                            }
                        }

                        if (haveChange == false)
                        {
                            dictOfAllMembers[forceSide].Add(forceUser);
                            Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                        }
                    }
                }

                else if (dictOfAllMembers.ContainsKey(forceSide) == false)
                {
                    bool CheckIfUserAlreadyExist = false;

                    // This is were Test-Error 8 was triggerd in my code
                    // when the member was not moved to the newly created group !!!!
                    foreach (var item in dictOfAllMembers)
                    {
                        if (item.Value.Contains(forceUser))
                        {
                            // I think you can skip this boolean check
                            CheckIfUserAlreadyExist = true;

                            // Repeat the same sequence as above
                            //currentSide = item.Key;

                            //Important, create the new group and then have it take up the
                            //member from the other side
                            //dictOfAllMembers[forceSide] = new List<string>();
                            //dictOfAllMembers[currentSide].Remove(forceUser);
                            //dictOfAllMembers[forceSide].Add(forceUser);
                            //Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                            //haveChange = true;

                        }
                    }

                    if (CheckIfUserAlreadyExist == false)
                    {
                        dictOfAllMembers[forceSide] = new List<string>();
                        dictOfAllMembers[forceSide].Add(forceUser);
                        Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                    }

                }

            }

1
Elena123456 avatar Elena123456 235 Точки

Hello Axiomatik and thanks for your quick responce. :)

I've already understood the idea of this ForceBook. I've tryed to refactoring my code added this, but the result is still 90/100.

  else if(dictOfAllMembers.ContainsKey(forceSide) == false)
                    {
                        bool theUserAlreadyExist = false;
                        string currentSide = string.Empty;
                        foreach (var item in dictOfAllMembers)
                        {
                            if (item.Value.Contains(forceUser))
                            {
                                theUserAlreadyExist = true;
                                currentSide = item.Key;
                            }
                        }

                        if (theUserAlreadyExist == true)
                        {
                            dictOfAllMembers[currentSide].Remove(forceUser);//can remove the user
                            dictOfAllMembers[forceSide] = new List<string>();
                            dictOfAllMembers[forceSide].Add(forceUser);
                            Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                        }

                        else if(theUserAlreadyExist == false)
                        {
                            dictOfAllMembers[forceSide] = new List<string>();
                            dictOfAllMembers[forceSide].Add(forceUser);
                            Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                        }


                    }
 

1
Axiomatik avatar Axiomatik 2422 Точки

OK, I am going to take a look at the whole code tomorrow. You can compare your solution with my code and maybe you can find out what's not working.

Best,

 

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

namespace forcebook
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<string, List<string>> sideList = new Dictionary<string, List<string>>();
            string command = Console.ReadLine();

            while (command != "Lumpawaroo")
            {
                string user = string.Empty;
                string side = string.Empty;
                if (command.Contains(" | "))
                {
                    string[] spliter = command.Split(" | ", StringSplitOptions.RemoveEmptyEntries);
                    if (spliter.Length < 2)
                    {
                        command = Console.ReadLine();
                        continue;
                    }
                    side = spliter[0];
                    user = spliter[1];
                    AddOperator(side, user, sideList);
                }
                else if (command.Contains(" -> "))
                {
                    string[] spliter = command.Split(" -> ");
                    side = spliter[1];
                    user = spliter[0];
                    SideOperator(side, user, sideList);
                }

                command = Console.ReadLine();
            }
            SortReverse(sideList);
            sideList = sideList.OrderByDescending(x => x.Value.Count).
                ThenBy(x => x.Key).ToDictionary(key => key.Key, value => value.Value);
            ListPrinter(sideList);
        }

        static void ListPrinter(Dictionary<string, List<string>> sideList)
        {
            foreach (var side in sideList)
            {
                int counter = 0;
                if (side.Value.Count >= 1)
                {
                    Console.WriteLine($"Side: {side.Key}, Members: {side.Value.Count}");
                    while (counter != side.Value.Count)
                    {
                        Console.WriteLine($"! {side.Value[counter]}");
                        counter++;
                    }

                }
            }
        }

        static Dictionary<string, List<string>> SortReverse(Dictionary<string, List<string>> sideList)
        {
            foreach (var side in sideList)
            {
                side.Value.Sort();
            }


            return sideList;
        }

        static Dictionary<string, List<string>> AddOperator(string side, string user, Dictionary<string, List<string>> sideList)
        {
            if (!sideList.ContainsKey(side))
            {
                sideList.Add(side, new List<string>());
                foreach (var group in sideList)
                {
                    int index = 0;
                    while (index != group.Value.Count)
                    {
                        string currentUser = group.Value[index];
                        string searchUser = user;

                        if (currentUser == searchUser)
                        {
                            return sideList;
                        }
                        index++;
                    }
                }
                sideList[side].Add(user);
                return sideList;
            }
            else
            {
                foreach (var group in sideList)
                {
                    int index = 0;
                    while (index != group.Value.Count)
                    {
                        string currentUser = group.Value[index];
                        string searchUser = user;

                        if (currentUser == searchUser)
                        {
                            return sideList;
                        }
                        index++;
                    }
                }
                sideList[side].Add(user);
            }
            return sideList;
        }

        static Dictionary<string, List<string>> SideOperator(string side, string user, Dictionary<string, List<string>> sideList)
        {
            foreach (var group in sideList)
            {
                if (group.Key == side)
                {
                    foreach (var member in group.Value)
                    {
                        if (member == user)
                        {
                            Console.WriteLine($"{user} joins the {side} side!");
                            return sideList;
                        }
                    }
                }
            }

            if (!sideList.ContainsKey(side))
            {
                sideList.Add(side, new List<string>());
                foreach (var group in sideList)
                {
                    foreach (var person in group.Value)
                    {
                        if (person == user)
                        {
                            group.Value.Remove(user);
                            sideList[side].Add(user);
                            Console.WriteLine($"{user} joins the {side} side!");
                            return sideList;
                        }
                    }
                }
            }
            else
            {
                foreach (var group in sideList)
                {
                    foreach (var person in group.Value)
                    {
                        if (person == user)
                        {
                            group.Value.Remove(user);
                            sideList[side].Add(user);
                            Console.WriteLine($"{user} joins the {side} side!");
                            return sideList;
                        }
                    }
                }

            }
            sideList[side].Add(user);
            Console.WriteLine($"{user} joins the {side} side!");
            return sideList;
        }
    }
}

1
Axiomatik avatar Axiomatik 2422 Точки

OK, so I compared with my code and the only difference I was able to pick up was at lines 53-56, when an user is re-joining his own group.

I've also used an expanded input to test new cases, so try to come up with new possible cases when the code still doesn't give 100%.

Lighter | Royal

Darker | DCay

Ivan Ivanov -> Lighter

Ivan Ivanov -> Lighter

Ivan Ivanov -> PeshoMen

DCay -> Lighter

Zebra -> Lighter

Lumpawaroo

Code:

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

namespace dict
{
    class MainClass
    {
        public static void Main()
        {
            var dictOfAllMembers = new Dictionary<string, List<string>>();

            string input = string.Empty;

            while ((input = Console.ReadLine()) != "Lumpawaroo")
            {
                if (input.Contains('|'))
                {
                    string[] inputArray = input.Split(" | ").ToArray();
                    string forceSide = inputArray[0];
                    string forceUser = inputArray[1];
                    bool CheckIfUserAlreadyExist = false;
                    foreach (var item in dictOfAllMembers)
                    {
                        if (item.Value.Contains(forceUser))
                        {
                            CheckIfUserAlreadyExist = true;
                        }
                    }

                    if (dictOfAllMembers.ContainsKey(forceSide) == true && CheckIfUserAlreadyExist == false)
                    {
                        dictOfAllMembers[forceSide].Add(forceUser);
                    }

                    else if (dictOfAllMembers.ContainsKey(forceSide) == false && CheckIfUserAlreadyExist == false)
                    {
                        dictOfAllMembers[forceSide] = new List<string>();
                        dictOfAllMembers[forceSide].Add(forceUser);
                    }
                }
                else if (input.Contains('>'))
                {
                    string[] inputArray = input.Split(" -> ").ToArray();
                    string forceUser = inputArray[0];
                    string forceSide = inputArray[1];

                    if (dictOfAllMembers.ContainsKey(forceSide) == true)
                    {
                        bool haveChange = false;
                        List<string> listOfCurrentUsers = dictOfAllMembers[forceSide];
                        // Added this validation, when user is re-joining his own group
                        if (listOfCurrentUsers.Contains(forceUser) == true)
                        {
                            Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                        }
                        else if (listOfCurrentUsers.Contains(forceUser) == false)//if user doesn't contains in currentList
                        {
                            foreach (var item in dictOfAllMembers)
                            {
                                string currentSide = string.Empty;
                                if (item.Value.Contains(forceUser))//if user contains in dictionary where is
                                {
                                    currentSide = item.Key;
                                    dictOfAllMembers[currentSide].Remove(forceUser);//can remove the user
                                    dictOfAllMembers[forceSide].Add(forceUser);
                                    Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                                    haveChange = true;
                                    break;
                                }
                            }

                            if (haveChange == false)
                            {
                                dictOfAllMembers[forceSide].Add(forceUser);
                                Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                            }
                        }
                    }
                    else if (dictOfAllMembers.ContainsKey(forceSide) == false)
                    {
                        bool CheckIfUserAlreadyExist = false;
                        foreach (var item in dictOfAllMembers)
                        {
                            if (item.Value.Contains(forceUser))
                            {
                                dictOfAllMembers[forceSide] = new List<string>();
                                dictOfAllMembers[item.Key].Remove(forceUser);
                                dictOfAllMembers[forceSide].Add(forceUser);
                                CheckIfUserAlreadyExist = true;
                                break;
                            }
                        }

                        if (CheckIfUserAlreadyExist == false)
                        {
                            dictOfAllMembers[forceSide] = new List<string>();
                            dictOfAllMembers[forceSide].Add(forceUser);
                            Console.WriteLine($"{forceUser} joins the {forceSide} side!");
                        }
                    }
                }
            }

            foreach (var item in dictOfAllMembers
                .Where(x => x.Value.Count > 0)
                .OrderByDescending(x => x.Value.Count()).ThenBy(x => x.Key))
            {
                Console.WriteLine($"Side: {item.Key}, Members: {item.Value.Count()}");
                List<string> listOfUsers = dictOfAllMembers[item.Key];

                foreach (var users in listOfUsers.OrderBy(x => x))
                {
                    Console.WriteLine($"! {users}");
                }
            }
        }
    }
}

1
Axiomatik avatar Axiomatik 2422 Точки

Forget to insert a Console.WriteLine for lines 85-93:

                        bool CheckIfUserAlreadyExist = false;
                        foreach (var item in dictOfAllMembers)
                        {
                            if (item.Value.Contains(forceUser))
                            {
                                dictOfAllMembers[forceSide] = new List<string>();
                                dictOfAllMembers[item.Key].Remove(forceUser);
                                dictOfAllMembers[forceSide].Add(forceUser);
                                CheckIfUserAlreadyExist = true;
                                Console.WriteLine($"{forceUser} joins the {forceSide} side!"); // Added
                                break;
                            }
                        }

1
Elena123456 avatar Elena123456 235 Точки

@Axiomatik ,

thank you for taking the time to right me back, I really appreciated. Thanks to you I finally understood how to work with dictionaries. :)

Best regards,

Elena

0
Elena123456 avatar Elena123456 235 Точки

Already I have 100% working code, I'am so happy about that! :)  https://pastebin.com/21npTWuQ

Axiomatic, you were right- my mistake was when the user try to rejoin in the same force side. Then on the console should be write nothing.

You were right and for my first mistake- when the force side dosn't exist I have to check if the username already exist. And if the username exist first I have to found and delete, then join the username in the current force side.

Thank you so much about your help!

 

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