Menu
Coddy logo textTech

סיכום – פעולות HashMap

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-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}");
        }
    }
}

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר C# אונליין