복습 - HashMap 연산
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨. 66개 중 55번째.
챌린지
중급ProcessDictionary라는 메서드를 작성하여 Dictionary<string, int> inventory에서 고급 작업을 수행하세요. 메서드는 다음을 수행해야 합니다:
- operations 목록의 명령을 처리합니다:
COUNT:Total items: {count}를 출력합니다(여기서{count}는 서로 다른 키의 개수입니다). 그런 다음 성공 메시지를 출력합니다.ADD item quantity: 지정된 수량으로 새 item을 추가합니다(item이 이미 존재하면 수량을 증가시킵니다). 그런 다음 성공 메시지를 출력합니다.REMOVE item: inventory에서 지정된 item을 제거한 다음 성공 또는 실패 메시지를 출력합니다.UPDATE item quantity: item의 수량을 지정된 값으로 설정한 다음 성공 또는 실패 메시지를 출력합니다.FIND item: found인 경우{item}: {quantity}를 출력한 다음 성공 메시지를 출력합니다. found가 아닌 경우Not found를 출력한 다음 실패 메시지를 출력합니다.
- 각 operation에 대해 다음의 정확한 형식으로 상태 메시지를 출력합니다:
Operation {command} performed successfullyOperation {command} failed: {reason}. 여기서{reason}은 inventory에 item이 존재하지 않을 때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
REQUIRED OUTPUT FORMAT:
직접 해보기
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# 컴파일러