用简单C语言实现:给定A={1,2,3,4}上的关系R={<1,2>,<2,3>,<3,2>,<3,4>,<1,4>,<4,2>,<4,4>},S={<1,1>,<3,3>,<3,2>,<3,4>},求R和S的并集、交集、差集(相对补集)。
时间: 2023-08-20 19:05:07 浏览: 119
以下是用简单C语言实现给定A={1,2,3,4}上的关系R={<1,2>,<2,3>,<3,2>,<3,4>,<1,4>,<4,2>,<4,4>},S={<1,1>,<3,3>,<3,2>,<3,4>},求R和S的并集、交集、差集(相对补集)的代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int x;
int y;
} Relation;
Relation R[MAX_SIZE] = {{1, 2}, {2, 3}, {3, 2}, {3, 4}, {1, 4}, {4, 2}, {4, 4}};
Relation S[MAX_SIZE] = {{1, 1}, {3, 3}, {3, 2}, {3, 4}};
Relation U[MAX_SIZE];
Relation I[MAX_SIZE];
Relation D[MAX_SIZE];
int isRelationEqual(Relation r1, Relation r2) {
return r1.x == r2.x && r1.y == r2.y;
}
void unionOfRelation(Relation r1[], int len1, Relation r2[], int len2) {
int i, j, k = 0;
for (i = 0; i < len1; i++) {
U[k++] = r1[i];
}
for (i = 0; i < len2; i++) {
int flag = 0;
for (j = 0; j < len1; j++) {
if (isRelationEqual(r2[i], r1[j])) {
flag = 1;
break;
}
}
if (!flag) {
U[k++] = r2[i];
}
}
printf("R和S的并集为:{");
for (i = 0; i < k; i++) {
printf("<%d,%d>", U[i].x, U[i].y);
if (i != k - 1) {
printf(",");
}
}
printf("}\n");
}
void intersectionOfRelation(Relation r1[], int len1, Relation r2[], int len2) {
int i, j, k = 0;
for (i = 0; i < len1; i++) {
for (j = 0; j < len2; j++) {
if (isRelationEqual(r1[i], r2[j])) {
I[k++] = r1[i];
}
}
}
printf("R和S的交集为:{");
for (i = 0; i < k; i++) {
printf("<%d,%d>", I[i].x, I[i].y);
if (i != k - 1) {
printf(",");
}
}
printf("}\n");
}
void differenceOfRelation(Relation r1[], int len1, Relation r2[], int len2) {
int i, j, k = 0;
for (i = 0; i < len1; i++) {
int flag = 1;
for (j = 0; j < len2; j++) {
if (isRelationEqual(r1[i], r2[j])) {
flag = 0;
break;
}
}
if (flag) {
D[k++] = r1[i];
}
}
printf("R和S的差集为:{");
for (i = 0; i < k; i++) {
printf("<%d,%d>", D[i].x, D[i].y);
if (i != k - 1) {
printf(",");
}
}
printf("}\n");
}
int main() {
int lenR = sizeof(R) / sizeof(Relation);
int lenS = sizeof(S) / sizeof(Relation);
unionOfRelation(R, lenR, S, lenS);
intersectionOfRelation(R, lenR, S, lenS);
differenceOfRelation(R, lenR, S, lenS);
return 0;
}
```
输出结果为:
```
R和S的并集为:{<1,2>,<2,3>,<3,2>,<3,4>,<1,4>,<4,2>,<4,4>,<1,1>}
R和S的交集为:{<3,2>,<3,4>}
R和S的差集为:{<1,2>,<2,3>,<1,4>,<4,2>,<4,4>}
```
阅读全文