Menu
Coddy logo textTech

Ripasso - Operazioni con HashMap

Fa parte della sezione Logica e flusso del percorso C# di Coddy. Lezione 55 di 66.

challenge icon

Sfida

Medio

Crea un metodo chiamato ProcessDictionary che esegua operazioni avanzate su un inventario Dictionary<string, int>. Il metodo deve:

  1. Elaborare i comandi da un elenco di operazioni:
    • COUNT: stampa Total items: {count} (dove {count} è il numero di chiavi distinte), quindi stampa il messaggio di esito positivo
    • ADD item quantity: aggiunge un nuovo elemento con la quantità specificata (se l'elemento esiste, incrementa la sua quantità), quindi stampa il messaggio di esito positivo
    • REMOVE item: rimuove l'elemento specificato dall'inventario, quindi stampa il messaggio di esito positivo o negativo
    • UPDATE item quantity: imposta la quantità dell'elemento sul valore specificato, quindi stampa il messaggio di esito positivo o negativo
    • FIND item: se viene trovato, stampa {item}: {quantity} e poi il messaggio di esito positivo; se non viene trovato, stampa Not found e poi il messaggio di esito negativo
  2. Per ogni operazione, stampa un messaggio di stato in questo formato esatto:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason}. Dove {reason} è Item not found quando l'elemento non esiste nell'inventario
  3. Restituisci il dizionario dell'inventario aggiornato

Ad esempio, elaborando FIND orange su un inventario contenente orange: 3 dovrebbe stampare:
orange: 3
Operation FIND performed successfully

E elaborando REMOVE shoes quando shoes non è nell'inventario dovrebbe stampare:
Operation REMOVE failed: Item not found

Provalo tu

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)
    {
        // Il tuo codice qui
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Leggi la prima riga per verificare se l'inventario è in formato JSON
        string firstLine = Console.ReadLine();
        
        // Verifica se l'input per l'inventario è in formato JSON
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Elabora l'input JSON per l'inventario
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Dividi in corrispondenza delle virgole che non si trovano tra virgolette
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Estrai la chiave e il valore usando 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}");
        }
    }
}

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore C# online