Recap - Unique Items
Part of the Logic & Flow section of Coddy's Rust journey — lesson 64 of 66.
Challenge
EasyWrite a function get_unique_items that takes numbers and returns a vector containing only the unique values from the input.
Use a hash map to track which numbers you've already seen, then build a result vector containing only numbers that appear exactly once in the input.
Logic:
- Create a hash map to count occurrences of each number
- Iterate through the input vector and update the count for each number
- Create a result vector
- Iterate through the input vector again and add numbers that have a count of 1 to the result
- Return the result vector
Parameters:
numbers(Vec<i32>): A vector of integers that may contain duplicates
Returns: A vector containing only the numbers that appear exactly once in the input, in the order they first appeared (Vec<i32>)
Try it yourself
fn get_unique_items(numbers: Vec<i32>) -> Vec<i32> {
// Write code here
}
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