用C语言实现求集合的笛卡尔乘积
时间: 2024-03-24 13:35:57 浏览: 102
javascript笛卡尔积算法实现方法.docx
首先需要定义一个结构体来表示一个集合:
```
typedef struct {
int *elements; // 集合元素数组
int size; // 集合大小
} Set;
```
接下来,可以使用递归的方式来实现笛卡尔乘积的计算。具体实现如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *elements; // 集合元素数组
int size; // 集合大小
} Set;
// 初始化集合
void initSet(Set *set, int size) {
set->elements = (int *) malloc(size * sizeof(int));
set->size = size;
}
// 释放集合内存
void freeSet(Set *set) {
free(set->elements);
}
// 计算两个集合的笛卡尔积
void cartesianProduct(Set *set1, Set *set2, int *result, int *count) {
for (int i = 0; i < set1->size; i++) {
for (int j = 0; j < set2->size; j++) {
result[(*count)++] = set1->elements[i];
result[(*count)++] = set2->elements[j];
}
}
}
// 计算多个集合的笛卡尔积
void cartesianProductAll(Set **sets, int numSets, int *result, int *count) {
if (numSets == 1) {
for (int i = 0; i < sets[0]->size; i++) {
result[(*count)++] = sets[0]->elements[i];
}
} else {
int temp[sets[0]->size * sets[1]->size];
int tempCount = 0;
cartesianProduct(sets[0], sets[1], temp, &tempCount);
for (int i = 2; i < numSets; i++) {
int newTemp[sets[i]->size * tempCount];
int newTempCount = 0;
cartesianProduct(sets[i], &(Set){temp, tempCount}, newTemp, &newTempCount);
for (int j = 0; j < newTempCount; j++) {
temp[j] = newTemp[j];
}
tempCount = newTempCount;
}
for (int i = 0; i < tempCount; i++) {
result[(*count)++] = temp[i];
}
}
}
int main() {
Set set1, set2, set3;
initSet(&set1, 2);
set1.elements[0] = 1;
set1.elements[1] = 2;
initSet(&set2, 2);
set2.elements[0] = 3;
set2.elements[1] = 4;
initSet(&set3, 2);
set3.elements[0] = 5;
set3.elements[1] = 6;
Set *sets[] = {&set1, &set2, &set3};
int result[set1.size * set2.size * set3.size];
int count = 0;
cartesianProductAll(sets, 3, result, &count);
for (int i = 0; i < count; i += 3) {
printf("(%d, %d, %d)\n", result[i], result[i+1], result[i+2]);
}
freeSet(&set1);
freeSet(&set2);
freeSet(&set3);
return 0;
}
```
这段代码实现了三个集合的笛卡尔积计算,输出结果为:
```
(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)
```
阅读全文