Rust Set Symmetric Difference Function
Rust Arrays: Exercise-4 with Solution
Write a Rust function that takes two sets as input and returns a new set containing elements that are present in either of the input sets, but not in both.
Sample Solution:
Rust Code:
use std::collections::HashSet;
// Define a function to find the symmetric difference between two sets
fn symmetric_difference(set1: &HashSet<i32>, set2: &HashSet<i32>) -> HashSet<i32> {
let mut symmetric_difference_set = HashSet::new();
// 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) {
symmetric_difference_set.insert(element);
}
}
// 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) {
symmetric_difference_set.insert(element);
}
}
symmetric_difference_set
}
fn main() {
let set1: HashSet<i32> = vec![1, 2, 3].into_iter().collect();
let set2: HashSet<i32> = vec![3, 4, 5].into_iter().collect();
let symmetric_diff = symmetric_difference(&set1, &set2);
println!("Symmetric Difference: {:?}", symmetric_diff);
}
Output:
Symmetric Difference: {2, 1, 4, 5}
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 symmetric_difference(set1: &HashSet<i32>, set2: &HashSet<i32>) -> HashSet<i32> { ... }: This line defines a function named symmetric_difference that takes two sets (HashSet<i32>) as input references and returns a new set containing elements that are present in either of the input sets, but not in both. It iterates over each element in both input sets and adds elements that are present in one set but not the other to the 'symmetric_difference_set'.
- The "main()" function serves as the entry point of the program. It creates two sets 'set1' and 'set2', each initialized with a vector of integers. Then, it calls the "symmetric_difference()" function with these sets as arguments to find the symmetric difference between them.
- The resulting symmetric difference set is stored in the 'symmetric_diff' variable.
- Finally, the symmetric difference set 'symmetric_diff' is printed to the console using println!.
Rust Code Editor:
Previous: Rust Set Difference Function.
Next: Rust Check Subset 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://www.w3resource.com/rust/collections_and_data_structures/rust-sets-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics