Recap - Manage Warehouse
Part of the Logic & Flow section of Coddy's C# journey — lesson 54 of 66.
Challenge
MediumCreate a warehouse inventory management system using dictionaries. Your task is to implement the ManageWarehouse method that performs the following operations:
- First, print all items and their quantities in format: "Item: [item], Quantity: [quantity]"
- Check if "apples" exist in inventory and print: "Apples in stock: [True/False]"
- Add 10 to the quantity of "bananas" if they exist (use direct value modification)
- Remove any item that has 0 quantity
- Print the total number of distinct items in the warehouse
- Finally, return the updated inventory dictionary
Try it yourself
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static Dictionary<string, int> ManageWarehouse(Dictionary<string, int> inventory)
{
// Your code here
return inventory;
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// Read first line to check if it's JSON format
string firstLine = Console.ReadLine();
// Check if input is in JSON format
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// Process JSON input
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// Split by commas that are not inside quotes
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// Extract key and value using 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);
}
}
}
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]));
}
}
Dictionary<string, int> result = ManageWarehouse(inventory);
// Print updated inventory
Console.WriteLine("Updated Inventory:");
foreach (var item in result)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}All lessons in Logic & Flow
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