Menu
Coddy logo textTech

Повторение — операции HashMap

Часть раздела Логика и управление потоком путешествия по C# на Coddy. Урок 55 из 66.

challenge icon

Задание

Средне

Создай метод с именем ProcessDictionary, который выполняет расширенные операции с inventory типа Dictionary<string, int>. Метод должен:

  1. Обрабатывать команды из списка operations:
    • COUNT: вывести Total items: {count} (где {count} — количество различных ключей), затем вывести сообщение об успешном выполнении
    • ADD item quantity: добавить новый item с указанным количеством (если item существует, увеличить его количество), затем вывести сообщение об успешном выполнении
    • REMOVE item: удалить указанный item из inventory, затем вывести сообщение об успешном или неуспешном выполнении
    • UPDATE item quantity: установить для item указанное значение количества, затем вывести сообщение об успешном или неуспешном выполнении
    • FIND item: если item найден, вывести {item}: {quantity}, затем сообщение об успешном выполнении; если item не найден, вывести Not found, затем сообщение о неуспешном выполнении
  2. Для каждой operation выводить сообщение о статусе в точно таком формате:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason}. Где {reason} — это Item not found, если item отсутствует в inventory
  3. Вернуть обновлённый словарь inventory

Например, при обработке FIND orange для inventory, содержащего orange: 3, должно быть выведено:
orange: 3
Operation FIND performed successfully

А при обработке REMOVE shoes, когда shoes отсутствует в inventory, должно быть выведено:
Operation REMOVE failed: Item not found REQUIRED OUTPUT FORMAT: [Your translated content here]

Попробуйте сами

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static Dictionary<string, int> ProcessDictionary(Dictionary<string, int> inventory, List<string> operations)
    {
        // Ваш код здесь
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Прочитать первую строку, чтобы проверить, является ли она JSON-форматом для inventory
        string firstLine = Console.ReadLine();
        
        // Проверить, является ли ввод JSON-форматом для inventory
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Обработать JSON-ввод для inventory
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Разделить по запятым, которые не находятся внутри кавычек
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Извлечь ключ и значение с помощью regex
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Read second line for operations
                string secondLine = Console.ReadLine();
                
                // Check if operations are in JSON array format
                if (secondLine != null && secondLine.StartsWith("[") && secondLine.EndsWith("]"))
                {
                    try
                    {
                        // Extract content between square brackets
                        string arrayContent = secondLine.Substring(1, secondLine.Length - 2);
                        
                        // Use regex to match all quoted strings - this is more robust
                        MatchCollection matches = Regex.Matches(arrayContent, @"""([^""]*)""");
                        
                        foreach (Match match in matches)
                        {
                            // Add the captured group (without quotes)
                            if (match.Groups.Count > 1)
                            {
                                operations.Add(match.Groups[1].Value);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error parsing operations array: {ex.Message}");
                        return;
                    }
                }
                else
                {
                    // Process operations in traditional format
                    int m = int.Parse(secondLine);
                    for (int i = 0; i < m; i++)
                    {
                        operations.Add(Console.ReadLine());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            // Process traditional input format
            int n = int.Parse(firstLine);
            for (int i = 0; i < n; i++)
            {
                string[] parts = Console.ReadLine().Split(':');
                inventory.Add(parts[0], int.Parse(parts[1]));
            }
            
            // Read operations
            int m = int.Parse(Console.ReadLine());
            for (int i = 0; i < m; i++)
            {
                operations.Add(Console.ReadLine());
            }
        }
        
        Dictionary<string, int> result = ProcessDictionary(inventory, operations);
        
        // Print updated inventory
        Console.WriteLine("Final Inventory:");
        foreach (var item in result)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Все уроки раздела Логика и управление потоком

Потренируйтесь самостоятельно: Онлайн-компилятор C#