Loading...

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

anton_fotev avatar anton_fotev 9 Точки

C# Associative arrays- exercise 9. ForceBook

Колеги, дава ми верни отговори на примерните задачи, но в Джъжда ме реже.


Условието е следното:


The force users are struggling to remember which side are the different forceUsers from, because they switch them
too often. So you are tasked to create a web application to manage their profiles. You should store information for
every unique forceUser, registered in the application.
You will receive several input lines in one of the following formats:
{forceSide} | {forceUser}
{forceUser} -> {forceSide}
The forceUser and forceSide are strings, containing any character.
If you receive forceSide | forceUser you should check if such forceUser already exists, and if not, add
him/her to the corresponding side.
If you receive a forceUser -> forceSide you should check if there is such forceUser already and if so, change
his/her side. If there is no such forceUser, add him/her to the corresponding forceSide, treating the command as
new registered forceUser.
Then you should print on the console: "{forceUser} joins the {forceSide} side!"
You should end your program when you receive the command "Lumpawaroo". At that point you should print each
force side, ordered descending by forceUsers count, than ordered by name. For each side print the forceUsers,
ordered by name.
In case there are no forceUsers in a side, you shouldn`t print the side information.
Input / Constraints
 The input comes in the form of commands in one of the formats specified above.
 The input ends when you receive the command "Lumpawaroo".
Output
 As output for each forceSide, ordered descending by forceUsers count, then by name, you must print all
the forceUsers, ordered by name alphabetically.
 The output format is:
Side: {forceSide}, Members: {forceUsers.Count}
! {forceUser}
! {forceUser}
! {forceUser}
 In case there are NO forceUsers, don`t print this side.

Примери:

входни данни                         резултат
Light | Gosho                          Side: Dark, Members: 1
Dark | Pesho                           ! Pesho
Lumpawaroo                           Side: Light, Members: 1
                                                ! Gosho

Lighter | Royal                         Ivan Ivanov joins the Lighter side!
Darker | DCay                         DCay joins the Lighter side!
Ivan Ivanov -> Lighter         Side: Lighter, Members: 3
DCay -> Lighter                  ! DCay
Lumpawaroo                           ! Ivan Ivanov
                                                ! Royal

Моят код:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
                    
public class Program
{
    public static void Main()
    {                
        string inputPrim = "";
        
        var listOfUsers = new Dictionary<string, string>();
        
        while((inputPrim = Console.ReadLine()) != "Lumpawaroo")
        {
         string[] input = inputPrim
             .Split()
             .ToArray();
            
        bool isLight = input[0] == "Light" || input[0] == "Lighter";
        bool isDark = input[0] == "Dark" || input[0] == "Darker";
            
          if (isLight || isDark)
          {              
            string nameUser = GetNameUser(input, 2, input.Length);           
              
            listOfUsers[nameUser] = input[0];
          }
            
          else // (!isLight && !isDark)
            {
             string nameUser = GetNameUser(input, 0, input.Length -2);                
                
             listOfUsers[nameUser] = input[input.Length -1];
                
             Console.WriteLine("{0} joins the {1} side!" , nameUser, input[input.Length -1]);    
            }        
        } // end wile
        
        var listLigthUsers = listOfUsers
            .Where( x => x.Value == "Light" || x.Value == "Lighter")
            .OrderBy(x => x.Key)
            .ToDictionary(x => x.Key,
                          x => x.Value);
        
        var listDarkUsers = listOfUsers
            .Where( x => x.Value == "Dark" || x.Value == "Darker")
            .OrderBy(x => x.Key)
            .ToDictionary(x => x.Key,
                          x => x.Value);
        
        if (listLigthUsers.Count > listDarkUsers.Count)
        {
         GetPrint(listLigthUsers);
         GetPrint(listDarkUsers);    
        }
        else
        {
         GetPrint(listDarkUsers);
         GetPrint(listLigthUsers);             
        }
    }
    
    public static string GetNameUser( string[] input, int start, int end)
    {
      StringBuilder currentName = new StringBuilder();
        
        for (int i = start; i < end; i++)
        {
         currentName.Append(input[i] + " ");
        }
        
        return currentName.ToString().Trim();
    }
    
    public static void GetPrint(Dictionary<string, string> listUsers)
    {
         if (listUsers.Count > 0)
        {
            string collor = "";
            
            foreach (var kvp in listUsers)
            {
             collor = kvp.Value;
             break;
            }
                
         Console.WriteLine("Side: {0}, Members: {1}", collor, listUsers.Count);
            foreach (var kvp in listUsers)
            {
              Console.WriteLine("! {0}", kvp.Key);
            }
            
        }
    }
}

// Light | Gosho
// Dark | Pesho
// Lumpawaroo
//Side: Dark, Members: 1
//! Pesho
//Side: Light, Members: 1
//! Gosho

// Lighter | Royal
// Darker | DCay
// Ivan Ivanov -> Lighter
// DCay -> Lighter
// Lumpawaroo
//Ivan Ivanov joins the Lighter side!
//DCay joins the Lighter side!
//Side: Lighter, Members: 3
//! DCay
//! Ivan Ivanov
//! Royal

0
Fundamentals Module
PetarIliev1 avatar PetarIliev1 73 Точки
Best Answer

Понеже съм я решавал тази задача но на Java това , което мога да ти кажа е ,че няма Lightside или Darkside има само side който си го пазиш във речник , примерният изход е забъркан ,ето ти едно решение на Java надявам се да ти помогне все някак https://pastebin.com/2USui2KX

0
20/06/2019 00:09:18
anton_fotev avatar anton_fotev 9 Точки

Благодаря за усилието да ми помогнеш.

Принципно и в курса на C# базовото решение започва така.
Тоест с речник, който има само два ключа - light or dark, като към всеки от двата ключа има стрингов лист с имената на юзърите.
Например нещо подобно: var listUsers = new Dictionary <string, List<string>>();

После съответно правиш проверки и когато съществуващ юзър се мести от side в side го ремувваш като стойност от стринговия лист към съответния кей. След малко ще седна и ще пробвам да реша задачата по този начин.

Пробвах задачата по моя начин, защото така се получава речник без нестнати стрингови листове. Тоест отделните юзъри са кей-ове в Речника и им променям директно value-то ( не се налага да ги трия от никъде).

Болката ми е да разбера при какви стойности ми дава грешни отговори в Джъд-жа, защото отчита и верни, и неверни.

 

0
PetarIliev1 avatar PetarIliev1 73 Точки

Вместо проверка за light or dark направи проверка дали инпъта е да добавиш user или да го преместиш тоест ( -> ) или ( | ).

Във Dictionary пази като ключ string а като стойност Set от string  ако не се лъжа можеш да го запазиш като SortedSet<string> което ще ти спести едно сортиране и една проверка за уникални users.

Dictionary <string,SortedSet<string>

Когато имаш команда да преместиш един user просто обходи речника и махай съответият user , той дори да не същестува това няма значение просто ще принтираш  (User joins the side!)

0
anton_fotev avatar anton_fotev 9 Точки

Сега ми дава 60/100

Утре, тоест днес, ще пробвам отново с речник, в който юзърите са Кей-ове.
За проба копи-пейстнах в Джъджа чуждо решение, което е изградено по логиката на първия ми вариант - с речник <string, string>, в който кей-овете са юзърите.

Настоящия ми код е следния:
П.П. Ако няма кой да помогне, ще пиша до самия СофтУни.

 

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

namespace _9A_test
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";

            var listUsers = new Dictionary<string, List<string>>();

            while ((input = Console.ReadLine()) != "Lumpawaroo")
            {
                var inputFirst = input
                     .Split(" | ")
                     .Select(x => x.Trim())
                     .ToArray();

                var inputTwo = input
                    .Split(" -> ")
                    .Select(x => x.Trim())
                    .ToArray();

                bool isNewUsers = inputFirst.Length > inputTwo.Length;

                if (isNewUsers)
                {
                    if (!listUsers.ContainsKey(inputFirst[0]))
                    {
                        listUsers[inputFirst[0]] = new List<string>();
                    }

                    if (!listUsers[inputFirst[0]].Contains(inputFirst[1]))
                    {
                        listUsers[inputFirst[0]].Add(inputFirst[1]);
                    }

                }

                else // !isNewUsers => .Split(" ->")
                {
                    foreach (var kvp in listUsers)
                    {
                        if (kvp.Value.Contains(inputTwo[0]))
                        {
                            kvp.Value.Remove(inputTwo[0]);
                        }
                    }

                    if (!listUsers.ContainsKey(inputTwo[1]))
                    {
                        listUsers[inputTwo[1]] = new List<string>();
                    }
                    listUsers[inputTwo[1]].Add(inputTwo[0]);

                    Console.WriteLine("{0} joins the {1} side!", inputTwo[0], inputTwo[1]);
          
                }

            } // end while

            listUsers = listUsers
                .OrderBy(x => x.Value.Count)
                .ThenBy(x => x.Key)
                .ToDictionary(x => x.Key,
                              x => x.Value);

            foreach (var kvp in listUsers)
            {
                if (kvp.Value.Count > 0)
                {
                    Console.WriteLine("Side: {0}, Members: {1}", kvp.Key, kvp.Value.Count);

                    foreach (var user in kvp.Value.OrderBy(x => x))
                    {
                        Console.WriteLine("! {0}", user);
                    }
                }
            }

        }
    }
}
 

 

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