Putting it all together
Part of the Logic & Flow section of Coddy's Rust journey — lesson 53 of 66.
Challenge
EasyYou will receive six inputs. The first input is a command that can be either add, check, or sell. The second input is an item name. The third input is a number representing either the quantity to sell (for sell command) or the initial quantity (for add command). The fourth input is a comma-separated list of item names in the inventory. The fifth input is a comma-separated list of prices corresponding to each item. The sixth input is a comma-separated list of quantities corresponding to each item.
Build a complete inventory management system that handles all three operations: adding items, checking stock, and selling items. Use a HashMap to store the inventory data where the key is the item name and the value is a tuple containing the price and quantity (f64, i32).
Requirements:
- Import
HashMapfromstd::collections - Read the first input (command) and trim whitespace
- Read the second input (item name) and trim whitespace
- Read the third input (quantity/price value) and trim whitespace
- Parse the third input to
f64 - Read the fourth input (comma-separated item names) and trim whitespace
- Read the fifth input (comma-separated prices) and trim whitespace
- Read the sixth input (comma-separated quantities) and trim whitespace
- Create a mutable
HashMap<String, (f64, i32)>for the inventory - Split the item names by commas
- Split the prices by commas and parse each to
f64 - Split the quantities by commas and parse each to
i32 - Insert each item into the inventory with its corresponding price and quantity as a tuple
- Use a
matchexpression on the command to determine which operation to perform - For
addcommand:- Use
.entry()and.or_insert()to add the item if it doesn't exist, using the third input as the price and0as the initial quantity - Print:
Added [item_name] to inventory - Print:
Price: $[price] - Print:
Quantity: 0
- Use
- For
checkcommand:- Use
.get()to check if the item exists - Use a
matchexpression to handle theOption - If
Some, print:[item_name] is in stockPrice: $[price]Quantity: [quantity]
- If
None, print:[item_name] is not in stock
- Use
- For
sellcommand:- Parse the third input to
i32as the quantity to sell - Use
.get()to check if the item exists - Use a
matchexpression to handle theOption - If
Some:- Check if current quantity is sufficient
- If yes, update the inventory with the new quantity and print:
Sold [quantity_to_sell] [item_name]Total: $[total_price]Remaining stock: [new_quantity]
- If no, print:
Insufficient stock for [item_name]Available: [current_quantity]
- If
None, print:[item_name] is not in stock
- Parse the third input to
- For any other command, print:
Invalid command
Input:
- First line: Command (
add,check, orsell) - Second line: Item name (e.g.,
Tablet) - Third line: Number (price for
add, quantity forsell, ignored forcheck) - Fourth line: Comma-separated item names (e.g.,
Laptop,Mouse,Keyboard) - Fifth line: Comma-separated prices (e.g.,
999.99,25.50,75.00) - Sixth line: Comma-separated quantities (e.g.,
15,50,30)
Output:
- For
addcommand:Added [item_name] to inventoryPrice: $[price]Quantity: 0
- For
checkcommand (item exists):[item_name] is in stockPrice: $[price]Quantity: [quantity]
- For
checkcommand (item doesn't exist):[item_name] is not in stock - For
sellcommand (sufficient stock):Sold [quantity_to_sell] [item_name]Total: $[total_price]Remaining stock: [new_quantity]
- For
sellcommand (insufficient stock):Insufficient stock for [item_name]Available: [current_quantity]
- For
sellcommand (item doesn't exist):[item_name] is not in stock - For invalid command:
Invalid command
Try it yourself
use std::collections::HashMap;
use std::io;
fn main() {
// Read inputs
let mut command = String::new();
io::stdin().read_line(&mut command).expect("Failed to read line");
let command = command.trim();
let mut item_name = String::new();
io::stdin().read_line(&mut item_name).expect("Failed to read line");
let item_name = item_name.trim();
let mut value_input = String::new();
io::stdin().read_line(&mut value_input).expect("Failed to read line");
let value_input = value_input.trim();
let mut items_input = String::new();
io::stdin().read_line(&mut items_input).expect("Failed to read line");
let items_input = items_input.trim();
let mut prices_input = String::new();
io::stdin().read_line(&mut prices_input).expect("Failed to read line");
let prices_input = prices_input.trim();
let mut quantities_input = String::new();
io::stdin().read_line(&mut quantities_input).expect("Failed to read line");
let quantities_input = quantities_input.trim();
// Create inventory HashMap
let mut inventory: HashMap<String, (f64, i32)> = HashMap::new();
// TODO: Write your code below
// Parse the comma-separated inputs and populate the inventory
// Use match expression on command to handle add, check, and sell operations
// Remember to output the appropriate messages based on the command
}All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together