Menu
Coddy logo textTech

Recap - HashMap Operations

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 55 de 66.

challenge icon

Desafío

Intermedio

Crea un método llamado ProcessDictionary que realiza operaciones avanzadas en un Dictionary<string, int> inventory. El método debe:

  1. Procesar comandos de una lista de operaciones:
    • COUNT: Imprime Total items: {count} (donde {count} es el número de claves distintas), luego imprime el mensaje de éxito
    • ADD item quantity: Agrega un nuevo elemento con la cantidad especificada (si el elemento existe, incrementa su cantidad), luego imprime el mensaje de éxito
    • REMOVE item: Elimina el elemento especificado del inventario, luego imprime el mensaje de éxito o fallo
    • UPDATE item quantity: Establece la cantidad del elemento al valor especificado, luego imprime el mensaje de éxito o fallo
    • FIND item: Si se encuentra, imprime {item}: {quantity} luego el mensaje de éxito; si no se encuentra, imprime Not found luego el mensaje de fallo
  2. Para cada operación, imprime un mensaje de estado en este formato exacto:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason} — donde {reason} es Item not found cuando el elemento no existe en el inventario
  3. Devuelve el diccionario de inventario actualizado

Por ejemplo, procesar FIND orange en un inventario que contiene orange: 3 debe imprimir:
orange: 3
Operation FIND performed successfully

Y procesar REMOVE shoes cuando shoes no está en el inventario debe imprimir:
Operation REMOVE failed: Item not found

Pruébalo tú mismo

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)
    {
        // Tu código aquí
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Lee la primera línea para verificar si tiene formato JSON para el inventario
        string firstLine = Console.ReadLine();
        
        // Verifica si la entrada está en formato JSON para el inventario
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Procesa la entrada JSON para el inventario
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Divide por comas que no estén dentro de comillas
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extrae la clave y el valor 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}");
        }
    }
}

Todas las lecciones de Lógica y Flujo