Menu
Coddy logo textTech

Recap - Manage Warehouse

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

challenge icon

チャレンジ

中級

Dictionary を使用した倉庫在庫管理システムを作成してください。以下の操作を実行する ManageWarehouse メソッドを実装するタスクです:

  1. まず、全アイテムとその数量を形式「Item: [item], Quantity: [quantity]」で出力してください
  2. 在庫に "apples" が存在するかを確認し、「Apples in stock: [True/False]」を出力してください
  3. 存在する場合、"bananas" の数量に 10 を追加してください(直接値の変更を使用)
  4. 数量が 0 のアイテムをすべて削除してください
  5. 倉庫内の異なるアイテムの総数を表示してください
  6. 最後に、更新された在庫 Dictionary を返してください

自分で試してみよう

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    public static Dictionary<string, int> ManageWarehouse(Dictionary<string, int> inventory)
    {
        // ここにコードを記述してください
        
        return inventory;
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // 1行目を読み込み、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)
                {
                    // 正規表現を使用してキーと値を抽出します
                    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);
                    }
                }
            }
            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]));
            }
        }
        
        Dictionary<string, int> result = ManageWarehouse(inventory);
        
        // Print updated inventory
        Console.WriteLine("Updated Inventory:");
        foreach (var item in result)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

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