w3resource

Rust Set Equality Function

Rust Arrays: Exercise-9 with Solution

Write a Rust function that checks whether two sets are equal (contain the same elements), regardless of the order of elements.

Sample Solution:

Rust Code:

use std::collections::HashSet; // Import the HashSet type from the standard library

// Define a function to check whether two sets are equal
fn are_sets_equal<T: Eq + std::hash::Hash>(set1: &HashSet<T>, set2: &HashSet<T>) -> bool {
    // Check if both sets have the same number of elements
    if set1.len() != set2.len() {
        return false; // If not, sets are not equal
    }

    // Check if every element in set1 is present in set2
    for element in set1 {
        if !set2.contains(element) {
            return false; // If any element of set1 is not found in set2, sets are not equal
        }
    }

    true // If all elements of set1 are found in set2, sets are equal
}

fn main() {
    // Create two sample sets
    let set1: HashSet<i32> = vec![1, 2, 3].into_iter().collect();
    let set2: HashSet<i32> = vec![3, 2, 1].into_iter().collect();

    // Check if the sets are equal
    let are_equal = are_sets_equal(&set1, &set2);

    // Print the result
    println!("Are the sets equal? {}", are_equal);
}

Output:

Are the sets equal? true

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::collections::HashSet;: Imports the "HashSet" type from the standard library, allowing us to use sets in our code.
  • fn are_sets_equal<T: Eq + std::hash::Hash>(set1: &HashSet<T>, set2: &HashSet<T>) -> bool { ... }: Defines a generic function named "are_sets_equal()" that takes two sets (HashSet<T>) as input references and returns a boolean value indicating whether the sets are equal. The function requires that the type 'T' implements the 'Eq' and 'Hash' traits.
  • The "are_sets_equal()" function first checks if the sets have the same number of elements. If not, the sets cannot be equal, so the function returns 'false'.
  • Then, the function iterates over each element in 'set1' and checks if it is present in 'set2'. If any element of 'set1' is not found in 'set2', the function returns 'false'. Otherwise, it returns 'true' after checking all elements.
  • The "main()" function serves as the entry point of the program. It creates two sample sets ('set1' and 'set2') with the same elements but in different orders, calls the "are_sets_equal()" function to check if the sets are equal, and prints the result.

Rust Code Editor:

Previous: Rust Set Cardinality Function.
Next: Rust Set Operations with Iterators.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.