Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

مراجعة - عمليات HashMap

جزء من قسم Logic & Flow في رحلة C# على Coddy — الدرس 55 من 66.

challenge icon

التحدي

متوسط

أنشئ طريقة تسمى ProcessDictionary تقوم بعمليات متقدمة على قاموس Dictionary<string, int> للمخزون. يجب أن تقوم الطريقة بما يلي:

  1. معالجة الأوامر من قائمة العمليات:
    • COUNT: طباعة Total items: {count} (حيث {count} هو عدد المفاتيح المميزة)، ثم طباعة رسالة النجاح
    • ADD item quantity: إضافة عنصر جديد بالكمية المحددة (إذا كان العنصر موجوداً، قم بزيادة كميته)، ثم طباعة رسالة النجاح
    • REMOVE item: إزالة العنصر المحدد من المخزون، ثم طباعة رسالة النجاح أو الفشل
    • UPDATE item quantity: تعيين كمية العنصر إلى القيمة المحددة، ثم طباعة رسالة النجاح أو الفشل
    • FIND item: إذا تم العثور عليه، اطبع {item}: {quantity} ثم رسالة النجاح؛ وإذا لم يتم العثور عليه، اطبع Not found ثم رسالة الفشل
  2. لكل عملية، اطبع رسالة حالة بهذا التنسيق الدقيق:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason} — حيث {reason} هو Item not found عندما لا يكون العنصر موجوداً في المخزون
  3. إرجاع قاموس المخزون المحدث

على سبيل المثال، معالجة FIND orange على مخزون يحتوي على orange: 3 يجب أن يطبع:
orange: 3
Operation FIND performed successfully

ومعالجة REMOVE shoes عندما لا يكون shoes موجوداً في المخزون يجب أن يطبع:
Operation REMOVE failed: Item not found

جرّب بنفسك

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)
    {
        // كودك هنا
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        List<string> operations = new List<string>();
        
        // قراءة السطر الأول للتحقق مما إذا كان بتنسيق JSON للمخزون
        string firstLine = Console.ReadLine();
        
        // التحقق مما إذا كان الإدخال بتنسيق JSON للمخزون
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // معالجة إدخال JSON للمخزون
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // التقسيم بواسطة الفواصل التي ليست داخل علامات الاقتباس
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // استخراج المفتاح والقيمة باستخدام 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}");
        }
    }
}

جميع دروس Logic & Flow