Rust Function: Check order of integers
Rust Pattern Maching: Exercise-7 with Solution
Write a Rust function that takes a slice of integers and returns "Ascending order!" if the integers are in ascending order, "Descending order!" if they are in descending order, and "Random" otherwise.
Sample Solution:
Rust Code:
// Function to check the order of integers in a slice.
fn check_order(slice: &[i32]) -> &'static str {
// Check if the slice is empty
if slice.is_empty() {
// If empty, return "Random"
return "Random";
}
// Check if the slice is sorted in ascending order
let is_ascending = slice.windows(2).all(|w| w[0] <= w[1]);
// Check if the slice is sorted in descending order
let is_descending = slice.windows(2).all(|w| w[0] >= w[1]);
// If all elements are in ascending order, return "Ascending order!"
if is_ascending {
"Ascending order!"
// If all elements are in descending order, return "Descending order!"
} else if is_descending {
"Descending order!"
// Otherwise, return "Random"
} else {
"Random order!"
}
}
fn main() {
// Example usage
let ascending = &[10, 20, 30, 40, 50];
let descending = &[50, 40, 30, 20, 10];
let random = &[30, 10, 40, 20, 50];
println!("{}", check_order(ascending)); // Output: Ascending order!
println!("{}", check_order(descending)); // Output: Descending order!
println!("{}", check_order(random)); // Output: Random
}
Output:
Ascending order! Descending order! Random order!
Explanation:
In the exercise above,
- The "check_order()" function takes a slice of integers (&[i32]) as input and returns a static string (&'static str) indicating the order of the integers.
- It first checks if the slice is empty. If it is, it returns "Random" because there is no meaningful order for an empty slice.
- It then uses the 'windows' iterator method to iterate over pairs of consecutive elements in the slice. It checks if all pairs satisfy the condition for ascending order (w[0] <= w[1]) and assigns the result to "is_ascending()". Similarly, it checks for descending order (w[0] >= w[1]) and assigns the result to "is_descending()".
- Depending on the values of "is_ascending()" and "is_descending()", the function returns the appropriate string:
- If all elements are in ascending order, it returns "Ascending order!"
- If all elements are in descending order, it returns "Descending order!"
- If neither of the above conditions is satisfied, it returns "Random order!"
Rust Code Editor:
Previous: Rust Function: Compare Tuple elements.
Next: Rust Function: Check character case.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/functional-programming/rust-pattern-matching-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics