Rust Program to Calculate union of two sets


Calculate union of two sets

Rust Programming Language


Calculate union of two sets


Problem


Rust program that calculates the union of two sets using the HashSet data structure.

Input


use std::collections::HashSet;

fn main() {
    let set1: HashSet<i32> = vec![1, 2, 3, 4, 5].into_iter().collect();
    let set2: HashSet<i32> = vec![3, 4, 5, 6, 7].into_iter().collect();
    let union: HashSet<&i32> = set1.union(&set2).collect();
    let union_vec: Vec<&i32> = union.iter().collect();
    println!("Union: {:?}", union_vec);
}{codeBox}

Output


Union: [1, 2, 3, 4, 5, 6, 7]{codeBox}

Explanation


This program creates two sets, set1 and set2, using HashSet. It then calculates their union using the union method provided by HashSet. Finally, it collects the union into a vector, union_vec, and prints it out.

Note that the order of the elements in the union vector may not be the same as their order in the original sets, as HashSet does not guarantee any particular order for its elements.


Post a Comment