w3resource

Rust Function: Process Tuples handling

Rust Pattern Maching: Exercise-10 with Solution

Write a Rust function that takes a vector of tuples (i32, i32) and returns the sum of all the first elements if the second elements are all even, the sum of all the second elements if the first elements are all odd, and 0 otherwise.

Sample Solution:

Rust Code:

// Function that processes a vector of tuples (i32, i32) and returns the sum of all the first elements
// if the second elements are all even, the sum of all the second elements if the first elements are
// all odd, and 0 otherwise.
fn process_tuples(tuples: Vec<(i32, i32)>) -> i32 {
    // Use iterators to extract first and second elements into separate vectors
    let (first_elements, second_elements): (Vec<_>, Vec<_>) = tuples.into_iter().unzip();
    
    // Check if all second elements are even
    let all_even = second_elements.iter().all(|&x| x % 2 == 0);
    // Check if all first elements are odd
    let all_odd = first_elements.iter().all(|&x| x % 2 != 0);

    // If all second elements are even, return the sum of all the first elements
    if all_even {
        first_elements.iter().sum()
    }
    // If all first elements are odd, return the sum of all the second elements
    else if all_odd {
        second_elements.iter().sum()
    }
    // Otherwise, return 0
    else {
        0
    }
}

fn main() {
    // Example usage
    let tuples1 = vec![(10, 20), (30, 40), (50, 60)]; // Second elements are all even
    let tuples2 = vec![(11, 30), (55, 70), (99, 11)]; // First elements are all odd
    let tuples3 = vec![(1, 2), (3, 4), (4, 7)]; // Neither condition satisfied

    println!("{}", process_tuples(tuples1)); // Output: 90 (10 + 30 + 50)
    println!("{}", process_tuples(tuples2)); // Output: 111 (30 + 70 + 11)
    println!("{}", process_tuples(tuples3)); // Output: 0
}

Output:

90
111
0

Explanation:

In the exercise above,

  • The "process_tuples()" function takes a vector of tuples (i32, i32) as input and returns 'i32'.
  • Inside the function, the "unzip()" method extracts the first and second elements of the tuples into separate vectors.
  • Two boolean variables, 'all_even' and 'all_odd', are calculated to determine if all second elements are even and all first elements are odd, respectively.
  • Depending on the conditions, the function either returns the sum of all the first elements, the sum of all the second elements, or 0.

Rust Code Editor:


Previous: Rust Function: Process result handling.
Next: Rust Function: Length of option string handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-10.php