Rust Check Superset Function
Rust Arrays: Exercise-6 with Solution
Write a Rust function that takes two sets as input and returns true if the first set is a superset 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 superset of the second set
fn is_superset(set1: &HashSet<i32>, set2: &HashSet<i32>) -> bool {
// Iterate over each element in the second set
for element in set2 {
// Check if the element is not present in the first set
if !set1.contains(element) {
// If any element of set2 is not found in set1, return false
return false;
}
}
// If all elements of set2 are found in set1, return true
true
}
fn main() {
// Create two sample sets
let set1: HashSet<i32> = vec![1, 2, 3, 4, 5].into_iter().collect();
let set2: HashSet<i32> = vec![1, 2, 3].into_iter().collect();
// Check if set1 is a superset of set2
let is_set1_superset_of_set2 = is_superset(&set1, &set2);
// Print the result
println!("Is set1 a superset of set2? {}", is_set1_superset_of_set2);
}
Output:
Is set1 a superset of set2? true
Explanation:
Here is a brief explanation of the above Rust code:
- 1. use std::collections::HashSet;: This line imports the "HashSet" type from the standard library, allowing us to use sets in our code.
2. fn is_superset(set1: &HashSet
, set2: &HashSet ) -> bool { ... }: This line defines a function named "is_superset()" that takes two sets (HashSet ) as input references and returns a boolean value indicating whether the first set is a superset of the second set. 3. The "is_superset()" function iterates over each element in the second set ('set2') and checks if it is present in the first set ('set1'). If any element of 'set2' is not found in 'set1', the function returns 'false'. Otherwise, it returns 'true' after checking all elements. 4. The "main()" function serves as the entry point of the program. It creates two sample sets ('set1' and 'set2') and calls the "is_superset()" function to check if 'set1' is a superset of 'set2'. Finally, it prints the result.
Rust Code Editor:
Previous: Rust Check Subset Function.
Next: Rust Set Conversion Function.
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/collections_and_data_structures/rust-sets-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics