gpt4 book ai didi

c - 查找数组之间的共同元素(匹配元素)

转载 作者:行者123 更新时间:2023-11-30 17:54:50 24 4
gpt4 key购买 nike

考虑一下我是否有一个输入,其中作为输入的数组数量不固定,并且每个数组中的元素数量也不固定。所以每次我的输入发生变化时,

 Example 1: 1st input

1st array= [2,3,4]
2nd array =[6,7,8,9]
3rd array=[5,3,12]

Example 2: 2nd input

1st array= [6,3,4,8]
2nd array =[6,7,4,9]
3rd array=[1,2,12]
4th array= [20,21,22,23,25]

所需的解决方案是,第一个数组被视为引用数组,下一组数组将相对于第一个数组(引用)进行检查,要求第二个数组不应有公共(public)元素第一个数组,然后继续检查第三个数组不应与第一个数组有公共(public)元素。

 from 1st Example 

1st array= [2,3,4] -- reference array
1st array= [2,3,4] is compared to 2nd array =[6,7,8,9]
1st array= [2,3,4] is compared to 3rd array=[5,3,12]

solution needed:
+ print 1st array( reference array)
+ if no common elements found between 1st array and 2nd array, from ex. no common elements found, so print out the 2nd array.
+ same for 3rd array, from ex. there is common element(3 is present in both first and third array), so dont print.

我已经尝试过将输入存储在二维数组中,但我搞砸了。请指导我使用您的算法/代码进行计算。

最佳答案

注意我如何创建一个数组来包含各个数组的长度,以及一个参数来告诉该数组有多长。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void print_array(int *a, int size) {
int i;
for (i = 0; i<size; i++) {
printf("%d ", a[i]);
}

printf("\n");
}


bool is_in(int *a, int size, int elem) {
int i;
for (i=0; i<size; i++) {
if (a[i] == elem) {
return true;
}
}
return false;
}

void f(int **a, int a_siz, int* sizes) {
print_array(a[0],sizes[0]);

for (int i=1; i< a_siz; i++) {
bool common_element = false;

for (int k=0; k< sizes[i]; k++) {
if (is_in(a[0],sizes[0],a[i][k])) {
common_element = true;
break;
}
}

if (! common_element) {
print_array(a[i],sizes[i]);
}
}

}



int main() {
int s = 3;
int sizes[] = {3,4,3};
int **a = malloc(sizeof(int*)*3);
for (int i=0; i<s; i++) {
a[i] = malloc(sizeof(int*)*sizes[i]);
}

a[0][0] = 2;
a[0][1] = 3;
a[0][2] = 4;

a[1][0] = 4;
a[1][1] = 7;
a[1][2] = 8;
a[1][3] = 9;

a[2][0] = 5;
a[2][1] = 44;
a[2][2] = 12;

f(a,s,&sizes);
}

关于c - 查找数组之间的共同元素(匹配元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14730409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com