復習 - HashMap の操作
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 55/66。
チャレンジ
中級ProcessDictionary という名前のメソッドを作成し、Dictionary<string, int> の inventory に対して高度な操作を実行します。このメソッドは次の処理を行う必要があります:
- operations のリストから command を処理する
COUNT:Total items: {count}を出力します({count}は重複しないキーの数です)。その後、success メッセージを出力しますADD item quantity:指定された quantity の新しい item を追加します(item が存在する場合は、その quantity を増加させます)。その後、success メッセージを出力しますREMOVE item:指定された item を inventory から削除し、その後 success または failed メッセージを出力しますUPDATE item quantity:item の quantity を指定された値に設定し、その後 success または failed メッセージを出力しますFIND item:found の場合は{item}: {quantity}を出力してから success メッセージを出力します。found でない場合はNot foundを出力してから failed メッセージを出力します
- 各 operation について、次の正確な形式でステータスメッセージを出力する
Operation {command} performed successfullyOperation {command} failed: {reason}。ここで{reason}は、item が inventory に存在しない場合はItem not foundです
- 更新された inventory Dictionary を return する
たとえば、
orange: 3 を含む inventory に対して FIND orange を処理すると、次のように出力されます:orange: 3Operation FIND performed successfullyshoes が 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>();
// 最初の行を読み取り、インベントリが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);
}
}
// 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#オンラインコンパイラ