Menu
CoddyTech

Ôn tập: Các thao tác với HashMap

Thuộc phần Logic và luồng chương trình trong hành trình C# của Coddy. Bài học 55 trên 66.

challenge icon

Thử thách

Trung bình

Tạo một phương thức tên là ProcessDictionary để thực hiện các thao tác nâng cao trên từ điển<string, int> lưu kho. Phương thức này cần:

  1. Xử lý các lệnh từ danh sách thao tác:
    • COUNT: In ra Total items: {count} (trong đó {count} là số khóa riêng biệt), sau đó in thông báo thành công
    • ADD item quantity: Thêm mặt hàng mới với số lượng đã chỉ định (nếu mặt hàng đã tồn tại, tăng số lượng của mặt hàng đó), sau đó in thông báo thành công
    • REMOVE item: Xóa mặt hàng đã chỉ định khỏi kho, sau đó in thông báo thành công hoặc thất bại
    • UPDATE item quantity: Đặt số lượng của mặt hàng thành giá trị đã chỉ định, sau đó in thông báo thành công hoặc thất bại
    • FIND item: Nếu tìm thấy, in ra {item}: {quantity}, sau đó in thông báo thành công; nếu không tìm thấy, in ra Not found, sau đó in thông báo thất bại
  2. Với mỗi thao tác, in thông báo trạng thái theo đúng định dạng sau:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason}. Trong đó, {reason} là Item not found khi mặt hàng không tồn tại trong kho
  3. Trả về từ điển kho đã cập nhật

Ví dụ, xử lý FIND orange trên kho có orange: 3 sẽ in ra:
orange: 3
Operation FIND performed successfully

Và xử lý REMOVE shoes khi shoes không có trong kho sẽ in ra:
Operation REMOVE failed: Item not found

Tự làm thử

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)
    {
        // Viết code của bạn ở đây
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // Đọc dòng đầu tiên để kiểm tra inventory có ở định dạng JSON không
        string firstLine = Console.ReadLine();
        
        // Kiểm tra đầu vào của inventory có ở định dạng JSON không
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Xử lý đầu vào JSON cho inventory
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Tách theo dấu phẩy nằm ngoài dấu ngoặc kép
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Dùng regex để trích xuất khóa và giá trị
                    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}");
        }
    }
}

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch C# online