Recap - HashMap Operations
Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 55 de 66.
Desafío
IntermedioCrea un método llamado ProcessDictionary que realiza operaciones avanzadas en un Dictionary<string, int> inventory. El método debe:
- Procesar comandos de una lista de operaciones:
COUNT: ImprimeTotal items: {count}(donde{count}es el número de claves distintas), luego imprime el mensaje de éxitoADD item quantity: Agrega un nuevo elemento con la cantidad especificada (si el elemento existe, incrementa su cantidad), luego imprime el mensaje de éxitoREMOVE item: Elimina el elemento especificado del inventario, luego imprime el mensaje de éxito o falloUPDATE item quantity: Establece la cantidad del elemento al valor especificado, luego imprime el mensaje de éxito o falloFIND item: Si se encuentra, imprime{item}: {quantity}luego el mensaje de éxito; si no se encuentra, imprimeNot foundluego el mensaje de fallo
- Para cada operación, imprime un mensaje de estado en este formato exacto:
Operation {command} performed successfullyOperation {command} failed: {reason}— donde{reason}esItem not foundcuando el elemento no existe en el inventario
- Devuelve el diccionario de inventario actualizado
Por ejemplo, procesar
FIND orange en un inventario que contiene orange: 3 debe imprimir:orange: 3Operation FIND performed successfullyY procesar
REMOVE shoes cuando shoes no está en el inventario debe imprimir:Operation REMOVE failed: Item not foundPruébalo tú mismo
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)
{
// Tu código aquí
return inventory;
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
List<string> operations = new List<string>();
// Lee la primera línea para verificar si tiene formato JSON para el inventario
string firstLine = Console.ReadLine();
// Verifica si la entrada está en formato JSON para el inventario
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// Procesa la entrada JSON para el inventario
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// Divide por comas que no estén dentro de comillas
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// Extrae la clave y el valor usando 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}");
}
}
}Todas las lecciones de Lógica y Flujo
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