Reputation: 4311
I need to write a program that checks if two arrays are equal, meaning that elements from array1 are all in array2. It is possible, that elements are in different rows and columns, but all the elements from the first array need to be in the second array. I wrote the code below:
#include <stdio.h>
int fun(int m, int tab1[][m], int tab2[][m], int n)
{
int i, j, k, p, itis = 0;
if(itis == 0)
{
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
int elem = tab2[i][j];
for(k=0; k<n; k++)
{
for(p=0; p<m; p++)
{
if(tab1[k][m] == elem)
{
itis = 1;
}
}
}
}
}
}
return itis;
}
int main()
{
int tab1[][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
int tab2[][3] = {{7,8,9}, {1,2,3}, {4,5,6}};
int tab3[][3] = {{0,0,0}, {0,0,0}, {0,0,1}};
int tab4[][3] = {{7,8,9}, {1,2,3}, {4,5,0}};
printf("%d\n", fun(3, tab1, tab4, 3));
return 0;
}
My function should return 1 if all the elements from the first array are present in the second array (could be in different order - rows/columns). But for tab1
and tab4
I got 1
, instead of 0
. (in tab1
there's 6, but 6 is not in tab4
). Any ideas?
Upvotes: 3
Views: 125
Reputation: 40155
int fun(int m, int tab1[][m], int tab2[][m], int n){
int *element1 = &tab1[0][0];//top element
int *endp1 = element1 + n*m;//end element
int *element2 = &tab2[0][0];
int *endp2 = element2 + n*m;
int itis = 0, *p;
for(;element1 != endp1; ++element1){
itis = 0;
for(p = element2; p != endp2; ++p){
if(*p == *element1){
itis = 1;//found!
break;
}
}
if(itis==0)//not found
return itis;//0
}
return itis;//1: all exist
}
Upvotes: 1