Rust Program to Check if a set is the subset of another set


Check if a set is the subset of another set

Rust Programming Language


Check if a set is the subset of another set


Problem


Rust program that checks if a set is a subset of another set.

Input


use std::collections::HashSet;

fn main() {
    // Create two sets of integers
    let set1: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();
    let set2: HashSet<i32> = [2, 4].iter().cloned().collect();
    let set3: HashSet<i32> = [6, 7].iter().cloned().collect();

    // Check if set2 is a subset of set1
    let is_subset1 = set2.is_subset(&set1);
    println!("set2 is a subset of set1: {}", is_subset1);

    // Check if set3 is a subset of set1
    let is_subset2 = set3.is_subset(&set1);
    println!("set3 is a subset of set1: {}", is_subset2);
}{codeBox}

Output


set2 is a subset of set1: true
set3 is a subset of set1: false{codeBox}

Explanation


In this example, we create two sets of integers using the HashSet data structure. We use the iter and cloned methods to convert arrays of integers into iterators of integer references, and then into cloned iterators of integers, which we can collect into sets.

We then check if set2 is a subset of set1 using the is_subset method, which returns true if all the elements in the first set are also in the second set. We print out the result using println!.

We also check if set3 is a subset of set1 using the is_subset method, and print out the result using println!.

This is the result of checking if set2 and set3 are subsets of set1. Since set2 contains only elements that are also in set1, it is a subset of set1. However, set3 contains elements that are not in set1, so it is not a subset of set1.


Post a Comment