Rust Function: Analyzing integer slice
Write a Rust function that takes a slice of integers and returns the sum of all elements if the sum is greater than 100, the product of all elements if the product is less than 100, and 0 otherwise.
Sample Solution:
Rust Code:
// Function that takes a slice of integers and returns a value based on the sum or product.
fn analyze_slice(slice: &[i32]) -> i32 {
// Check if the slice is empty
if slice.is_empty() {
// If empty, return 0
return 0;
}
// Calculate the sum of all elements
let sum: i32 = slice.iter().sum();
// Calculate the product of all elements
let product: i32 = slice.iter().product();
// If the sum is greater than 100, return the sum
if sum > 100 {
sum
// If the product is less than 100, return the product
} else if product < 100 {
product
// Otherwise, return 0
} else {
0
}
}
fn main() {
// Example usage
let slice1 = &[10, 20, 30, 40, 50]; // Sum > 100
let slice2 = &[1, 2, 3, 4]; // Product < 100
let slice3 = &[10, 20, 30, 10]; // Sum < 100, Product > 100
// Print the result for each slice
println!("{}", analyze_slice(slice1)); // Output: 150
println!("{}", analyze_slice(slice2)); // Output: 24
println!("{}", analyze_slice(slice3)); // Output: 0
}
Output:
150 24 0
Explanation:
In the exercise above,
- The function "analyze_slice()" takes a slice of integers (&[i32]) as input and returns an integer (i32) as output.
- It first checks if the slice is empty. If it is, it returns 0.
- Next, it calculates the sum and product of all elements in the slice using the "iter()" method combined with "sum()" and "product()" functions.
- Based on the values of the sum and product, it determines the return value:
- If the sum is greater than 100, it returns the sum.
- If the product is less than 100, it returns the product.
- Otherwise, it returns 0.
- In the "main()" function, example slices are provided, and the result of calling "analyze_slice()" on each slice is printed.
Rust Code Editor:
Previous: Rust Function: Analyzing Boolean vector.
Next: Rust Triangle Classifier function.
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