Recap - HashMap Operations
Часть раздела Логика и управление потоком путешествия по C# на Coddy — урок 55 из 66.
Задание
СреднеСоздайте метод с именем 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, когда элемент не существует в инвентаре
- Вернуть обновленный словарь инвентаря
Например, обработка
FIND orange на инвентаре, содержащем orange: 3, должна вывести:orange: 3Operation FIND performed successfullyА обработка
REMOVE shoes, когда 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)
{
// Извлечение ключа и значения с помощью 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}");
}
}
}Все уроки раздела Логика и управление потоком
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