实现集合的各种运算#c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int size;
} Jihe;
// 初始化集合
void initjihe(Jihe *s) {
s->size = 0;
}
int isinjihe(Jihe s, int x) {
for (int i = 0; i < s.size; i++) {
if (s.data[i] == x) {
return 1;
}
}
return 0;
}
void addtojihe(Jihe *s, int x) {
if (!isinjihe(*s, x)) {
s->data[s->size++] = x;
}
}
//删移动覆盖
void deletedata(Jihe *s, int x) {
for (int i = 0; i < s->size; i++) {
//0 1 2 3
//* * * *
if (s->data[i] == x) {
for (int j = i; j < s->size - 1; j++) {
s->data[j] = s->data[j + 1];
}
s->size--;
break;
}
}
}
//集合交集运算
Jihe Jiaojiys(Jihe s1, Jihe s2) {
//result 新集合
Jihe result;
initjihe(&result);
for (int i = 0; i < s1.size; i++) {
if (isinjihe(s2, s1.data[i])) {
addtojihe(&result, s1.data[i]);
}
}
return result;
}
//集合的并集运算
Jihe bingjiys(Jihe s1, Jihe s2) {
Jihe result;
initjihe(&result);
for (int i = 0; i < s1.size; i++) {
addtojihe(&result, s1.data[i]);
}
for (int i = 0; i < s2.size; i++) {
addtojihe(&result, s2.data[i]);
}
return result;
}
//集合的补集运算
Jihe bujiys(Jihe s, Jihe U) {
Jihe result;
initjihe(&result);
for (int i = 0; i < U.size; i++) {
if (!isinjihe(s, U.data[i])) {
addtojihe(&result, U.data[i]);
}
}
return result;
}
//集合的差集运算
Jihe chajiys(Jihe s1, Jihe s2) {
Jihe result;
initjihe(&result);
for (int i = 0; i < s1.size; i++) {
//s1 1 2 3 4
//s2 4 5 6 7
if (!isinjihe(s2, s1.data[i])) {
addtojihe(&result, s1.data[i]);
}
}
return result;
}
//对称差集运算
//s1⊕s2={{s1US2}-{s1^s2}}
//s1⊕s2={{s1-S2}U{s2-s1}}
Jihe DCCys(Jihe s1, Jihe s2) {
Jihe result;
initjihe(&result);
Jihe jiaoji = Jiaojiys(s1, s2);
Jihe cha1 = chajiys(s1, jiaoji);
Jihe cha2 = chajiys(s2, jiaoji);
result = bingjiys(cha1, cha2);
return result;
}
int main() {
//own
Jihe A, B;
initjihe(&A);
initjihe(&B);
printf("集合A的元素个数:\n->");
int n;
scanf("%d", &n);
printf("请输入集合A的元素:");
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
addtojihe(&A, x);
}
printf("请输入集合B的元素个数:\n->");
scanf("%d", &n);
printf("请输入集合B的元素:");
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
addtojihe(&B, x);
}
//全部结果
printf("A ∩ B=");
Jihe jiaoji = Jiaojiys(A, B);
if(jiaoji.size==0){
printf("Ø");
}
else{
for (int i = 0; i < jiaoji.size; i++) {
printf("%d ", jiaoji.data[i]);
}
}
printf("\n");
printf("A ∪ B=");
Jihe bingji = bingjiys(A, B);
for (int i = 0; i < bingji.size; i++) {
printf("%d ", bingji.data[i]);
}
printf("\n");
printf("A的补集=");
Jihe buji = bujiys(A, B);
if(buji.size==0){
printf("Ø");
}else{
for (int i = 0; i < buji.size; i++) {
printf("%d ", buji.data[i]);
}
}
printf("\n");
printf("A - B=");
Jihe chaji = chajiys(A, B);
if(chaji.size==0){
printf("Ø");
}else{
for (int i = 0; i < chaji.size; i++) {
printf("%d ", chaji.data[i]);
}
}
printf("\n");
printf("A ⊕ B=");
Jihe dccdata = DCCys(A, B);
if(dccdata.size==0){
printf("Ø");
}else{
for (int i = 0; i < dccdata.size; i++) {
printf("%d ", dccdata.data[i]);
}
}
printf("\n");
return 0;
}
//6.5
//----------------------------集合的各种运算--------------------------
0 评论