3

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?

4
  • Shouldn't that be if(tab1[k][p] == elem) ... ? However, the current code only checks for a single match. You could increment a count for each match found, then check to see if the count == m*n . Commented Jan 19, 2015 at 20:55
  • Your code doesn't define tab4 but your question mentions it. Commented Jan 19, 2015 at 20:57
  • See stackoverflow.com/questions/9120065/… for inspiration Commented Jan 19, 2015 at 20:57
  • 1
    Generally: Flatten, sort, compare. Commented Jan 19, 2015 at 21:16

1 Answer 1

1
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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.