📖 Scenario: You are managing a farm with several stalls placed along a straight line. You want to place cows in these stalls such that the minimum distance between any two cows is as large as possible. This helps prevent fights between cows.
🎯 Goal: Build a Rust program that finds the largest minimum distance possible between cows placed in given stalls.
📋 What You'll Learn
Create a vector called stalls with exact values [1, 2, 8, 4, 9]
Create an integer variable called cows and set it to 3
Write a function can_place_cows that checks if cows can be placed with at least a given minimum distance
Use binary search to find the maximum minimum distance
Print the maximum minimum distance found
💡 Why This Matters
🌍 Real World
This problem models placing resources or devices in locations to maximize minimum spacing, useful in network design, agriculture, and facility planning.
💼 Career
Understanding binary search on answer space and greedy feasibility checks is important for software engineering interviews and optimization problems.
Progress0 / 4 steps
1
Create the stalls vector
Create a vector called stalls with the exact values [1, 2, 8, 4, 9].
DSA Rust
Hint
Use let mut stalls = vec![1, 2, 8, 4, 9]; to create the vector.
2
Add the cows variable
Add an integer variable called cows and set it to 3 inside the main function after the stalls vector.
DSA Rust
Hint
Use let cows = 3; to create the variable.
3
Write the can_place_cows function and sort stalls
Write a function called can_place_cows that takes stalls: &Vec<i32>, cows: i32, and distance: i32 and returns bool. It should check if it is possible to place all cows in stalls such that the minimum distance between any two cows is at least distance. Also, sort the stalls vector inside main before calling this function.
DSA Rust
Hint
Sort the stalls using stalls.sort();. The function should count how many cows can be placed with at least the given distance.
4
Find and print the maximum minimum distance
Use binary search in main to find the maximum minimum distance to place all cows in stalls. Use the can_place_cows function to check feasibility. Print the maximum minimum distance found using println!("{}", max_distance);.
DSA Rust
Hint
Use binary search between 1 and the max distance between first and last stall. Update max_distance when placement is possible.
Practice
(1/5)
1. What is the main goal of the Aggressive Cows Maximum Minimum Distance problem?
easy
A. To place cows in stalls so that the minimum distance between any two cows is as large as possible
B. To place cows in stalls so that the maximum distance between any two cows is as small as possible
C. To find the total number of cows that can fit in all stalls
D. To calculate the average distance between all cows placed in stalls
Solution
Step 1: Understand the problem objective
The problem asks to place cows in given stalls such that the smallest distance between any two cows is as large as possible.
Step 2: Clarify the goal
This means maximizing the minimum distance between cows, ensuring they are as far apart as possible.
Final Answer:
To place cows in stalls so that the minimum distance between any two cows is as large as possible -> Option A
Quick Check:
Maximize minimum distance = To place cows in stalls so that the minimum distance between any two cows is as large as possible [OK]
Hint: Maximize the smallest gap between cows placed [OK]
Common Mistakes:
Confusing maximum minimum distance with minimum maximum distance
Thinking the problem is about total cows fitting
Assuming average distance is the goal
2. Which of the following Rust code snippets correctly sorts the stall positions stored in a vector stalls for the Aggressive Cows problem?
easy
A. stalls.sort_by(|a, b| b.cmp(a));
B. stalls.sorted();
C. stalls.sort();
D. stalls.order();
Solution
Step 1: Identify the correct Rust method to sort a vector
In Rust, the method sort() sorts a vector in ascending order in place.
Step 2: Check other options
sorted() does not exist on vectors, sort_by with reversed order sorts descending, and order() is invalid.
Final Answer:
stalls.sort(); -> Option C
Quick Check:
Use sort() to sort vector in Rust [OK]
Hint: Use stalls.sort() to sort vector ascending in Rust [OK]
Common Mistakes:
Using non-existent methods like sorted()
Sorting in descending order by mistake
Trying to assign result of sort() which returns ()
3. Given the Rust code below, what is the output printed?
let stalls = vec![1, 2, 8, 4, 9];
let cows = 3;
let mut sorted_stalls = stalls.clone();
sorted_stalls.sort();
fn can_place_cows(stalls: &Vec<i32>, cows: i32, dist: i32) -> bool {
let mut count = 1;
let mut last_pos = stalls[0];
for &pos in stalls.iter().skip(1) {
if pos - last_pos >= dist {
count += 1;
last_pos = pos;
if count == cows {
return true;
}
}
}
false
}
let mut low = 1;
let mut high = sorted_stalls[sorted_stalls.len() - 1] - sorted_stalls[0];
let mut result = 0;
while low <= high {
let mid = (low + high) / 2;
if can_place_cows(&sorted_stalls, cows, mid) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
println!("{}", result);
Hint: Binary search distances, check feasibility with can_place_cows [OK]
Common Mistakes:
Not sorting stalls before binary search
Incorrect binary search boundaries
Miscounting cows placed in can_place_cows
4. Identify the bug in the following Rust function used in the Aggressive Cows problem and select the correct fix:
fn can_place_cows(stalls: &Vec<i32>, cows: i32, dist: i32) -> bool {
let mut count = 0;
let mut last_pos = stalls[0];
for &pos in stalls.iter() {
if pos - last_pos >= dist {
count += 1;
last_pos = pos;
if count == cows {
return true;
}
}
}
false
}
medium
A. Initialize count to cows instead of 0
B. Both A and B
C. Start loop from stalls.iter().skip(1) instead of stalls.iter()
D. No bug, function is correct
Solution
Step 1: Analyze initial count and loop start
Count should start at 1 because first cow is placed at stalls[0]. Loop should skip first stall to avoid counting it twice.
Step 2: Fix both initialization and loop
Set count = 1 and loop with stalls.iter().skip(1) to correctly count cows placed.
Final Answer:
Both A and B -> Option B
Quick Check:
Count=1 and skip first stall in loop [OK]
Hint: Start count at 1 and skip first stall in loop [OK]
Common Mistakes:
Starting count at 0 causes off-by-one error
Looping from first stall counts first cow twice
Returning false incorrectly due to wrong count
5. You have stalls at positions [2, 5, 11, 15, 17, 20] and want to place 4 cows. Using the Aggressive Cows approach, what is the maximum minimum distance you can achieve between any two cows?