用Set实现数学集合的交并差,交集外所有的元素

import javafx.animation.SequentialTransition;

import java.util.*;

public class Sets {
    //求并集
    public static <T> Set<T> union(Set<T> a, Set<T> b) {
        Set<T> result = new HashSet<T>(a);
        result.addAll(b);
        return result;
    }

    //求交集
    public static <T> Set<T> intersection(Set<T> a, Set<T> b) {
        Set<T> result = new HashSet<T>(a);
        result.retainAll(b);
        return result;

    }

    //求差集
    public static <T> Set<T> difference(Set<T> a, Set<T> b) {
        Set<T> result = new HashSet<>(a);
        result.removeAll(b);
        return result;
    }

    //求交集外所有元素
    public static <T> Set<T> complement(Set<T> a, Set<T> b) {
        return difference(union(a,b),intersection(a,b));

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例程序: ```c #include <stdio.h> #define MAX_SIZE 10 int main() { int set1[MAX_SIZE], set2[MAX_SIZE], union_set[MAX_SIZE], intersection_set[MAX_SIZE], complement_set[MAX_SIZE]; int n1, n2, i, j, k, flag; // 输入第一个集合 printf("Enter the size of set 1: "); scanf("%d", &n1); printf("Enter the elements of set 1: "); for (i = 0; i < n1; i++) { scanf("%d", &set1[i]); } // 输入第二个集合 printf("Enter the size of set 2: "); scanf("%d", &n2); printf("Enter the elements of set 2: "); for (i = 0; i < n2; i++) { scanf("%d", &set2[i]); } // 计算并集 k = 0; for (i = 0; i < n1; i++) { union_set[k++] = set1[i]; } for (i = 0; i < n2; i++) { flag = 1; for (j = 0; j < n1; j++) { if (set2[i] == set1[j]) { flag = 0; break; } } if (flag) { union_set[k++] = set2[i]; } } printf("The union of set 1 and set 2 is: "); for (i = 0; i < k; i++) { printf("%d ", union_set[i]); } printf("\n"); // 计算交集 k = 0; for (i = 0; i < n1; i++) { for (j = 0; j < n2; j++) { if (set1[i] == set2[j]) { intersection_set[k++] = set1[i]; } } } printf("The intersection of set 1 and set 2 is: "); for (i = 0; i < k; i++) { printf("%d ", intersection_set[i]); } printf("\n"); // 计算补集 k = 0; for (i = 0; i < n1; i++) { flag = 1; for (j = 0; j < n2; j++) { if (set1[i] == set2[j]) { flag = 0; break; } } if (flag) { complement_set[k++] = set1[i]; } } printf("The complement of set 1 with respect to set 2 is: "); for (i = 0; i < k; i++) { printf("%d ", complement_set[i]); } printf("\n"); return 0; } ``` 程序中定义了 `set1` 和 `set2` 分别表示两个输入的集合,`union_set`、`intersection_set` 和 `complement_set` 分别表示它们的并集、交集和补集。程序先分别输入两个集合,然后按照离散数学中的定义计算并集、交集和补集,并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值