Rust Vector sorting & slicing
Witre a Rust program that creates a vector of random integers. Sort the vector in ascending order and slice it to get a sub-vector containing the top 3 elements. Print the sub-vector.
Sample Solution:
Rust Code:
use rand::prelude::*; // Import the necessary traits for random number generation
fn main() {
// Create a vector to store random integers
let mut numbers: Vec = Vec::new(); // Declare an empty vector to store integers
// Initialize the random number generator
let mut rng = thread_rng(); // Create a random number generator instance
// Generate random integers and add them to the vector
for _ in 0..10 {
// Generate a random integer between 1 and 100
let num = rng.gen_range(1..=100); // Use the gen_range method to generate random numbers within a range
numbers.push(num); // Add the generated number to the vector
}
// Sort the vector in ascending order
numbers.sort(); // Use the sort method to sort the vector
// Slice the vector to get a sub-vector containing the top 3 elements
let top_three = &numbers[numbers.len() - 3..]; // Slice the vector from the third last element to the end
// Print the sub-vector containing the top 3 elements
println!("Top three elements: {:?}", top_three); // Print the sub-vector using debug formatting
}
Output:
Top three elements: [70, 91, 92]
Explanation:
Here is a brief explanation of the above Rust code:
- use rand::prelude::*;: This line imports the necessary traits for random number generation from the 'rand' crate.
- fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
- let mut numbers: Vec<i32> = Vec::new();: This line declares an empty vector named numbers to store integers.
- let mut rng = thread_rng();: This line creates an instance of the random number generator.
- for _ in 0..10 { ... }: This line starts a loop to generate 10 random integers.
- let num = rng.gen_range(1..=100);: This line generates a random integer between 1 and 100 using the "gen_range()" method.
- numbers.push(num);: This line adds the generated random number to the vector numbers.
- numbers.sort();: This line sorts the vector 'numbers' in ascending order using the sort method.
- let top_three = &numbers[numbers.len() - 3..];: This line slices the vector to get a sub-vector containing the top 3 elements.
- println!("Top three elements: {:?}", top_three);: This line prints the sub-vector containing the top 3 elements using debug formatting.
Rust Code Editor:
Previous: Rust Vector manipulation & slicing.
Next: Rust Array access guide.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics