📖 Scenario: You are packing a bag for a hiking trip. You have several items, each with a weight and a value. Your bag can only carry a limited weight. You want to maximize the total value of items in your bag. You can take fractions of items if needed.
🎯 Goal: Build a Rust program that calculates the maximum value you can carry in your bag using the fractional knapsack approach.
📋 What You'll Learn
Create a vector of tuples called items where each tuple contains weight and value as f64.
Create a variable called capacity of type f64 representing the maximum weight the bag can carry.
Sort the items vector by value-to-weight ratio in descending order.
Calculate the maximum value that fits in the bag using fractional parts of items if needed.
Print the maximum value with two decimal places.
💡 Why This Matters
🌍 Real World
This problem models packing and resource allocation where partial quantities can be taken, such as loading cargo or budgeting.
💼 Career
Understanding greedy algorithms like fractional knapsack is useful for optimization problems in software engineering, logistics, and finance.
Progress0 / 4 steps
1
Create the list of items
Create a vector called items with these exact tuples of (weight, value) as f64: (10.0, 60.0), (20.0, 100.0), (30.0, 120.0).
DSA Rust
Hint
Use let mut items: Vec<(f64, f64)> = vec![(10.0, 60.0), (20.0, 100.0), (30.0, 120.0)];
2
Set the bag capacity
Create a variable called capacity of type f64 and set it to 50.0.
DSA Rust
Hint
Use let capacity: f64 = 50.0; to set the bag capacity.
3
Sort items by value-to-weight ratio and calculate max value
Sort the items vector by value-to-weight ratio in descending order using sort_by. Then create a variable total_value of type f64 set to 0.0. Use a for loop with variables weight and value to iterate over items. Inside the loop, if capacity is zero, break. Otherwise, take the minimum of weight and capacity as amount. Add amount * (value / weight) to total_value. Subtract amount from capacity.
DSA Rust
Hint
Sort with items.sort_by(|a, b| ((b.1 / b.0).partial_cmp(&(a.1 / a.0))).unwrap()); and use a loop to add fractional values.
4
Print the maximum value
Print the total_value rounded to two decimal places using println!("{:.2}", total_value);.
DSA Rust
Hint
Use println!("{:.2}", total_value); to print the result.
Practice
(1/5)
1. What is the main goal of the Fractional Knapsack Problem?
easy
A. Maximize total value by taking fractions of items within weight limit
B. Minimize total weight by selecting whole items only
C. Maximize number of items regardless of weight
D. Select items randomly without considering value or weight
Solution
Step 1: Understand problem objective
The fractional knapsack problem aims to maximize the total value of items placed in a knapsack without exceeding its weight capacity.
Step 2: Recognize fractional selection
Unlike the 0/1 knapsack, it allows taking fractions of items to fill the knapsack optimally.
Final Answer:
Maximize total value by taking fractions of items within weight limit -> Option A
Quick Check:
Goal = maximize value with fractions [OK]
Hint: Remember: fractional means partial items allowed [OK]
Common Mistakes:
Thinking only whole items can be taken
Confusing with minimizing weight
Ignoring value-to-weight ratio
2. Which Rust code snippet correctly defines a struct to represent an item with weight and value for the fractional knapsack?
easy
A. struct Item { weight: usize, value: bool }
B. struct Item { weight: f64, value: f64 }
C. struct Item { weight: String, value: String }
D. struct Item(weight: i32, value: i32);
Solution
Step 1: Identify correct struct syntax
Rust structs use curly braces with field names and types, e.g., struct Item { weight: f64, value: f64 }.
Step 2: Check field types for fractional knapsack
Weights and values can be fractional, so f64 (floating-point) is appropriate.
Take full (5,30), remaining 15, total value 30. Take full (10,40), remaining 5, total value 70. Take fraction of (15,45): fraction = 5/15 = 1/3, value = 45 * 1/3 = 15. Total value = 70 + 15 = 85.
Step 3: Verify options
85 is 85, matching calculation.
Final Answer:
85 -> Option C
Quick Check:
Greedy fill with fractions = 85 [OK]
Hint: Sort by ratio, fill capacity fully, then fractionally [OK]
Common Mistakes:
Not sorting by ratio
Taking items in wrong order
Incorrect fraction calculation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.