Tuesday, August 6, 2024

BCA PART A 1.R program to implement operations of set (union, intersection, difference, subset).

 

Explanation

  1. Union: The union() function combines all elements from both sets, removing duplicates.
  2. Intersection: The intersect() function finds the common elements between the two sets.
  3. Difference: The setdiff() function finds elements in one set that are not in the other.
    • setdiff(set_A, set_B) finds elements in set_A that are not in set_B.
    • setdiff(set_B, set_A) finds elements in set_B that are not in set_A.
  4. Subset:
    • The expression all(set_A %in% set_B) checks if all elements of set_A are in set_B, indicating that set_A is a subset of set_B.
    • The expression all(set_B %in% set_A) checks if all elements of set_B are in set_A, indicating that set_B is a subset of set_A.
    • A proper subset is determined by checking if one set is a subset of the other but not vice versa.

Program

# Define two sets as vectors
set_A <- c(1, 2, 3, 4, 5)
set_B <- c(4, 5, 6, 7, 8)


# Union of sets
union_set <- union(set_A, set_B)
cat("Union of set_A and set_B:\n")
print(union_set)


# Intersection of sets
intersection_set <- intersect(set_A, set_B)
cat("\nIntersection of set_A and set_B:\n")
print(intersection_set)


# Difference of sets (set_A - set_B)
difference_set_A_B <- setdiff(set_A, set_B)
cat("\nDifference of set_A - set_B:\n")
print(difference_set_A_B)


# Difference of sets (set_B - set_A)
difference_set_B_A <- setdiff(set_B, set_A)
cat("\nDifference of set_B - set_A:\n")
print(difference_set_B_A)


# Check if set_A is a subset of set_B
is_subset_A_B <- all(set_A %in% set_B)
cat("\nIs set_A a subset of set_B?:\n")
print(is_subset_A_B)


# Check if set_B is a subset of set_A
is_subset_B_A <- all(set_B %in% set_A)
cat("\nIs set_B a subset of set_A?:\n")
print(is_subset_B_A)


# Check if a set is a proper subset
is_proper_subset_A_B <- all(set_A %in% set_B) && !all(set_B %in% set_A)
cat("\nIs set_A a proper subset of set_B?:\n")
print(is_proper_subset_A_B)

Output :

Union of set_A and set_B:
[1] 1 2 3 4 5 6 7 8

Intersection of set_A and set_B:
[1] 4 5

Difference of set_A - set_B:
[1] 1 2 3

Difference of set_B - set_A:
[1] 6 7 8

Is set_A a subset of set_B?:
[1] FALSE

Is set_B a subset of set_A?:
[1] FALSE

Is set_A a proper subset of set_B?:
[1] FALSE

=== Session Ended. Please Run the code again ===

No comments:

Post a Comment