Recap - HashMap Operations
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 55번째.
챌린지
중급ProcessDictionary라는 메서드를 생성하여 Dictionary<string, int> inventory에 고급 작업을 수행하세요. 이 메서드는 다음을 수행해야 합니다:
- 작업 목록의 명령어를 처리하세요:
COUNT:Total items: {count}을 출력하세요 (여기서{count}는 고유 키의 개수입니다), 그런 다음 성공 메시지를 출력하세요ADD item quantity: 지정된 수량으로 새 항목을 추가하세요 (항목이 존재하면 수량을 증가시키세요), 그런 다음 성공 메시지를 출력하세요REMOVE item: 지정된 항목을 재고에서 제거하세요, 그런 다음 성공 또는 실패 메시지를 출력하세요UPDATE item quantity: 항목의 수량을 지정된 값으로 설정하세요, 그런 다음 성공 또는 실패 메시지를 출력하세요FIND item: 찾은 경우{item}: {quantity}을 출력한 후 성공 메시지를 출력하세요; 찾지 못한 경우Not found을 출력한 후 실패 메시지를 출력하세요
- 각 작업에 대해 정확히 이 형식으로 상태 메시지를 출력하세요:
Operation {command} performed successfullyOperation {command} failed: {reason}— 여기서{reason}은 항목이 재고에 존재하지 않을 때Item not found입니다
- 업데이트된 재고 사전을 반환하세요
예를 들어,
orange: 3을 포함하는 재고에서 FIND orange를 처리하면 다음을 출력해야 합니다:orange: 3Operation FIND performed successfully그리고 재고에
shoes가 없을 때 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>();
// 첫 번째 줄을 읽어 inventory가 JSON 형식인지 확인합니다
string firstLine = Console.ReadLine();
// 입력이 inventory를 위한 JSON 형식인지 확인합니다
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// inventory를 위한 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}");
}
}
}논리 및 흐름의 모든 레슨
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety