Menu
Coddy logo textTech

Powtórka — operacje na HashMap

Część sekcji Logika i sterowanie przepływem ścieżki C# w Coddy. Lekcja 55 z 66.

challenge icon

Wyzwanie

Średni

Utwórz metodę o nazwie ProcessDictionary, która wykonuje zaawansowane operacje na magazynie typu Dictionary<string, int>. Metoda powinna:

  1. Przetwarzać polecenia z listy operacji:
    • COUNT: Wypisać Total items: {count} (gdzie {count} to liczba różnych kluczy), a następnie wypisać komunikat o powodzeniu
    • ADD item quantity: Dodać nowy element z określoną ilością (jeśli element już istnieje, zwiększyć jego ilość), a następnie wypisać komunikat o powodzeniu
    • REMOVE item: Usunąć określony element z magazynu, a następnie wypisać komunikat o powodzeniu lub niepowodzeniu
    • UPDATE item quantity: Ustawić ilość elementu na określoną wartość, a następnie wypisać komunikat o powodzeniu lub niepowodzeniu
    • FIND item: Jeśli element zostanie znaleziony, wypisać {item}: {quantity}, a następnie komunikat o powodzeniu; jeśli nie zostanie znaleziony, wypisać Not found, a następnie komunikat o niepowodzeniu
  2. Dla każdej operacji wypisać komunikat o statusie w dokładnie takim formacie:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason}. Gdzie {reason} to Item not found, gdy element nie istnieje w magazynie
  3. Zwrócić zaktualizowany słownik magazynu

Na przykład, wykonanie FIND orange na magazynie zawierającym orange: 3 powinno wypisać:
orange: 3
Operation FIND performed successfully

A wykonanie REMOVE shoes, gdy shoes nie ma w magazynie, powinno wypisać:
Operation REMOVE failed: Item not found

Spróbuj swoich sił

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)
    {
        // Twój kod tutaj
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Odczytaj pierwszy wiersz, aby sprawdzić, czy dane magazynowe są w formacie JSON
        string firstLine = Console.ReadLine();
        
        // Sprawdź, czy dane wejściowe dotyczące stanu magazynowego są w formacie JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Przetwórz dane wejściowe JSON dotyczące stanu magazynowego
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Podziel według przecinków, które nie znajdują się wewnątrz cudzysłowów
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Wyodrębnij klucz i wartość za pomocą wyrażenia regularnego
                    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}");
        }
    }
}

Wszystkie lekcje w sekcji Logika i sterowanie przepływem

Poćwicz samodzielnie: Kompilator C# online