Menu
Coddy logo textTech

Recap - HashMap Operations

Part of the Logic & Flow section of Coddy's C# journey — lesson 55 of 66.

challenge icon

Challenge

Medium

Create a method called ProcessDictionary that performs advanced operations on a Dictionary<string, int> inventory. The method should:

  1. Process commands from a list of operations:
    • COUNT: Print Total items: {count} (where {count} is the number of distinct keys), then print the success message
    • ADD item quantity: Add a new item with the specified quantity (if item exists, increment its quantity), then print the success message
    • REMOVE item: Remove the specified item from inventory, then print the success or failure message
    • UPDATE item quantity: Set the item's quantity to the specified value, then print the success or failure message
    • FIND item: If found, print {item}: {quantity} then the success message; if not found, print Not found then the failure message
  2. For each operation, print a status message in this exact format:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason} — where {reason} is Item not found when the item does not exist in the inventory
  3. Return the updated inventory dictionary

For example, processing FIND orange on an inventory containing orange: 3 should print:
orange: 3
Operation FIND performed successfully

And processing REMOVE shoes when shoes is not in the inventory should print:
Operation REMOVE failed: Item not found

Try it yourself

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)
    {
        // Your code here
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Read first line to check if it's JSON format for inventory
        string firstLine = Console.ReadLine();
        
        // Check if input is in JSON format for inventory
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Process JSON input for inventory
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Split by commas that are not inside quotes
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extract key and value using 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}");
        }
    }
}

All lessons in Logic & Flow