Menu
Coddy logo textTech

Recap - HashMap Operations

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 55/66。

challenge icon

チャレンジ

中級

ProcessDictionary という名前のメソッドを作成し、Dictionary<string, int> inventory に対して高度な操作を実行します。このメソッドは次のことを行うべきです:

  1. operations のリストからコマンドを処理します:
    • COUNTTotal items: {count} を出力(ここで {count} は異なるキーの数)、その後成功メッセージを出力
    • ADD item quantity: 指定された数量で新しいアイテムを追加(アイテムが存在する場合はその数量を増加)、その後成功メッセージを出力
    • REMOVE item: inventory から指定されたアイテムを削除し、その後成功または失敗メッセージを出力
    • UPDATE item quantity: アイテムの数量を指定された値に設定し、その後成功または失敗メッセージを出力
    • FIND item: 見つかった場合、{item}: {quantity} を出力し成功メッセージ;見つからない場合、Not found を出力し失敗メッセージ
  2. 各操作に対して、この正確な形式でステータスメッセージを出力:
    • Operation {command} performed successfully
    • Operation {command} failed: {reason} — ここで {reason} は、アイテムが inventory に存在しない場合に Item not found
  3. 更新された inventory 辞書を返します

例: orange: 3 を含む inventory に対して FIND orange を処理すると、以下を出力します:
orange: 3
Operation FIND performed successfully

また、shoes が inventory にない場合に REMOVE 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>();
        
        // 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}");
        }
    }
}

ロジックとフローのすべてのレッスン