2013-02-06 185 views
0

请考虑如果我有一个输入,其中输入的数组数量不固定,并且每个数组中的元素数量也不固定。因此,每个我的输入而变化的时间,查找数组之间的公共元素(匹配元素)

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] 

需要的解决方案是,第一阵列被认为是一个参考阵列,下一组阵列被相对于所述第一阵列(参考)进行检查,要求是第二个数组不应该有第一个数组的公共元素,并且它会继续下一个检查第三个数组不应该有第一个数组的公共元素。

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. 

我试图通过存储输入在2维数组,但我搞砸了。 请指导我使用你的算法/代码来计算这个值。

+1

你是如何得到输入的?从一个文件?从'stdin'?请显示获取输入的代码示例以及尝试使用消除冗余的算法 – Mike

+0

另外:找到一个或多个匹配元素时,您不希望打印整个数组,包括不匹配的元素? – ArjunShankar

+0

对参考数组进行排序。二进制搜索查找。 – SparKot

回答

0

请注意,我不得不创建一个数组来包含各种数组的长度,以及一个参数来说明数组的长度。

#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); 
} 
0

由于问题指出数组的长度不是常数,静态二维数组的想法可能无法工作。您可以使用DMA(malloc和calloc函数)创建2维阵列

您可能更喜欢直接转发算法,它将参考数组中的每个元素与其他数组进行比较。

+0

大部分人都会错过这个..这是一次对一个人的战斗。 :)付出代价并传播这个词 – Mike