|
发表于 2021-3-18 23:46:56
|
显示全部楼层
本楼为最佳答案
 作业要自己做,这次决定帮你了,但是你总不能指望别人一直帮你做作业吧
- #include <stdio.h>
- #include <string.h>
- #include <stdbool.h>
- void intersection_set(const int a[], size_t a_size, const int b[], size_t b_size, int c[], size_t *c_size, size_t c_max_size) {
- for(size_t i = 0; i < a_size; ++i) {
- for(size_t j = 0; j < b_size; ++j) {
- if(a[i] == b[j]) {
- if(*c_size >= c_max_size) return;
- c[(*c_size)++] = a[i];
- }
- }
- }
- }
- void union_set(const int a[], size_t a_size, const int b[], size_t b_size, int c[], size_t *c_size, size_t c_max_size) {
- if(a_size >= c_max_size) return;
- memcpy(c, a, sizeof(a[0]) * a_size);
- *c_size = a_size;
- for(size_t i = 0; i < b_size; ++i) {
- bool flag = true;
- for(size_t j = 0; j < *c_size; ++j) {
- if(b[i] == c[j]) {
- flag = false;
- break;
- }
- }
- if(*c_size >= c_max_size) return;
- if(flag) c[(*c_size)++] = b[i];
- }
- }
- void print(int a[], size_t size) {
- for(size_t i = 0; i < size; ++i) {
- printf("%d ", a[i]);
- }
- printf("\n");
- }
- int main(void) {
- int a[] = {1 ,9, 2, 7, 5, 3};
- int b[] = {1 ,8, 2, 6, 9};
- int c[100];
- int d[100];
- size_t a_size = 6;
- size_t b_size = 5;
- size_t c_size = 0;
- size_t d_size = 0;
- size_t c_max_size = 100;
- size_t d_max_size = 100;
- intersection_set(a, a_size, b, b_size, c, &c_size, c_max_size);
- union_set(a, a_size, b, b_size, d, &d_size, d_max_size);
- printf("a:\n"); print(a, a_size);
- printf("b:\n"); print(b, b_size);
- printf("c:\n"); print(c, c_size);
- printf("d:\n"); print(d, d_size);
- return 0;
- }
复制代码 |
|