w3resource

Rust Check Subset Function

Rust Arrays: Exercise-5 with Solution

Write a Rust function that takes two sets as input and returns true if the first set is a subset of the second set, otherwise returns false.

Sample Solution:

Rust Code:

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

// Define a function to check if the first set is a subset of the second set
fn is_subset(set1: &HashSet<i32>, set2: &HashSet<i32>) -> bool {
    // Iterate over each element in the first set
    for element in set1 {
        // Check if the element is not present in the second set
        if !set2.contains(element) {
            // If any element of set1 is not found in set2, return false
            return false;
        }
    }

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

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

    // Check if set1 is a subset of set2
    let is_set1_subset_of_set2 = is_subset(&set1, &set2);

    // Print the result
    println!("Is set1 a subset of set2? {}", is_set1_subset_of_set2);
}

Output:

Is set1 a subset of set2? true

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::collections::HashSet;: This line imports the "HashSet" type from the standard library, allowing us to use sets in our code.
  • fn is_subset(set1: &HashSet<i32>, set2: &HashSet<i32>) -> bool { ... }: This line defines a function named is_subset that takes two sets (HashSet<i32>) as input references and returns a boolean value indicating whether the first set is a subset of the second set.
  • The "is_subset()" function iterates over each element in the first set ('set1') and checks if it is present in the second set ('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') and calls the "is_subset()" function to check if 'set1' is a subset of 'set2'. Finally, it prints the result.

Rust Code Editor:

Previous: Rust Set Symmetric Difference Function.
Next: Rust Check Superset Function.

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://www.w3resource.com/rust/collections_and_data_structures/rust-sets-exercise-5.php