Menu
Coddy logo textTech

Récapitulatif - Opérations HashMap

Fait partie de la section Logique & Flux du Journey C# de Coddy — leçon 55 sur 66.

challenge icon

Défi

Moyen

Créez une méthode appelée ProcessDictionary qui effectue des opérations avancées sur un inventaire Dictionary<string, int>. La méthode doit :

  1. Traiter les commandes d'une liste d'opérations :
    • COUNT : Afficher Total items: {count} (où {count} est le nombre de clés distinctes), puis afficher le message de succès
    • ADD item quantity : Ajouter un nouvel article avec la quantité spécifiée (si l'article existe, incrémenter sa quantité), puis afficher le message de succès
    • REMOVE item : Supprimer l'article spécifié de l'inventaire, puis afficher le message de succès ou d'échec
    • UPDATE item quantity : Définir la quantité de l'article à la valeur spécifiée, puis afficher le message de succès ou d'échec
    • FIND item : S'il est trouvé, afficher {item}: {quantity} puis le message de succès ; s'il n'est pas trouvé, afficher Not found puis le message d'échec
  2. Pour chaque opération, afficher un message d'état dans ce format exact :
    • Operation {command} performed successfully
    • Operation {command} failed: {reason} — où {reason} est Item not found lorsque l'article n'existe pas dans l'inventaire
  3. Retourner le dictionnaire d'inventaire mis à jour

Par exemple, le traitement de FIND orange sur un inventaire contenant orange: 3 devrait afficher :
orange: 3
Operation FIND performed successfully

Et le traitement de REMOVE shoes quand shoes n'est pas dans l'inventaire devrait afficher :
Operation REMOVE failed: Item not found

Essayez vous-même

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)
    {
        // Votre code ici
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Lire la première ligne pour vérifier s'il s'agit du format JSON pour l'inventaire
        string firstLine = Console.ReadLine();
        
        // Vérifier si l'entrée est au format JSON pour l'inventaire
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Traiter l'entrée JSON pour l'inventaire
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Diviser par les virgules qui ne sont pas entre guillemets
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extraire la clé et la valeur à l'aide de 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}");
        }
    }
}

Toutes les leçons de Logique & Flux