Problem with intersection of two arrays in C

Smokeweeds :

when trying to intersect two arrays, I'd like to show only the numbers that repeats twice , tried creating a variable that counts the number of repetitions on both arrays and put a condition, ex : if(r1 + r2>2 ) but i have trouble making it work ._.

example :

#include <stdio.h>
#define N1 5
#define N2 5
#define N3 5
int main()
{
    int i=0,T1[5]={1,1,6,9,12},T2[5]={1,2,7,9,12},T3[5],j=0,k=0,tmp;


    for(i=0;i<N1;i++)
    {
        for(j=0;j<N1;j++)
        {
            if(T1[i]==T2[j]){
                T3[k]=T1[i];
                k++;}}

        }
    for(j=0;j<N1-1;j++)
    {
        for(k=0;k<N1-1;k++)
        {
            if(T3[k]<T3[k+1]){
                tmp=T3[k];
                T3[k]=T3[k+1];
                T3[k+1]=tmp;}
        }
    }

    for(k=0;k<N3;k++)
    {
        printf("This is the array after intersection  : T[%d] = %d\n",k,T3[k]);
    }

}```

Output : This is the array after intersection : T[0] = (random numbers)
         This is the array after intersection : T[1] = (random numbers)
         This is the array after intersection : T[2] = 12
         This is the array after intersection : T[3] = 9
         This is the array after intersection : T[4] = 1


hitter :

You don't have to save the values to a third array T3 you can simply return them, once they are found to be part of the intersection of the arrays T1 and T2.
Something like the code below will work fine:

#include <stdio.h>

#define N1 5
#define N2 5
#define N3 5

void intersection(int* T1, int* T2) {
    int i = 0, j = 0;
    printf("The intersection of the 2 arrays is: ");
    while (i < N1 && j < N2){
        if (T1[i] < T2[j]) {
            i++;
        }
        else if (T2[j] < T1[i]) {
            j++;
        }
        else // if T1[i] == T2[j]
        {
            printf("%d ", T2[j]);
            j++;
            i++;
        }
    }
    printf("\n");
    return;
}

int main(void) {
    int i = 0, j = 0, k = 0, tmp,
        T1[N1] = { 1, 1, 6, 9, 12 },
        T2[N2] = { 1, 2, 7, 9, 12 };
    intersection(T1, T2);
    return 0;
}

When run this code outputs:

The intersection of the 2 arrays is: 1 9 12

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33188&siteId=1