Home > Blockchain >  Comparing 2 arrays to find out if they have the same elements or not
Comparing 2 arrays to find out if they have the same elements or not

Time:10-21

I'm a beginner programmer and i needed some help with an exercise! As you saw in the title the exercise asks to write a program that compares the elements of 2 arrays to find out if they have the same elements or not. The trick is that the elements on the 2nd array may not be in the same order as the ones in the first array. I thought that maybe one way to fix this is to rearrange the 2 arrays for them to be in ascending order but for some reason it keeps saying that the arrays have the same elements. Can you help me?

This is the code:

int main()
{
    int v[N];
    int v2[N];
    int i,j;
    int a;
    int b;
    int flag = 0;

    printf("Please enter the values of the 1st array: ");

    for (i = 0; i < N; i  )
    {
        scanf("%d",&v[i]);
    }

    for (i = 0; i < N; i  )
    {
        for(j=i 1; j<N; j  )
        {
            if(v[i]>v[j])
            {
                a = v[i];
                v[i] = v[j];
                v[j] = a;
            }
        }
    }

    printf("\nPlease enter the values of the 2nd array: ");
    
    for (i = 0; i < N; i  )
    {
        scanf("%d", &v2[i]);
    }

    for (i = 0; i < N; i  )
    {
        for (j = i   1; j < N; j  )
        {
            if (v2[i] > v2[j])
            {
                b = v2[i];
                v2[i] = v2[j];
                v2[j] = b;
            }
        }
    }

    for (i = 0; i < N; i  )
    {
        for (j = 0; j < N; j  )
        {
            if (v[i] == v2[j])
            {
                flag=1;
            }
        }
    }

    if (flag == 1)
        printf("\nThe arrays have the same numbers! ");
    else
        printf("\nThe arrays dont have the same numbers!");

    return 0;
}

CodePudding user response:

There may be other issues, but the main issue I see here is this:

for(i=0;i<N;i  )
{
    for(j=0;j<N;j  )
    {
        if(v[i]==v2[j])
        {
            flag=1;
        }
    }
}

What this is saying is for each element in the first array, check each element in the second array; if it is equal to the element in the first array, then set flag = 1. Essentially, it returns true if ANY of the elements are the same in the two arrays.

CodePudding user response:

The sorting loops seem correct, but the comparison loop is not: you compare every item from the first array to every item of the second array, so the result will be true if any number of the first array is present in the second array, which is a much weaker condition.

You should use a much simpler comparison loop, comparing v[i] and v2[i].

Here is a modified version:

#include <stdio.h>

#define N  100

int main() {
    int v[N];
    int v2[N];
    int i, j;
    int flag;

    printf("Please enter the values of the 1st array: ");

    for (i = 0; i < N; i  ) {
        if (scanf("%d", &v[i]) != 1)
            return 1;
    }

    for (i = 0; i < N; i  ) {
        for (j = i   1; j < N; j  ) {
            if (v[i] > v[j]) {
                int a = v[i];
                v[i] = v[j];
                v[j] = a;
            }
        }
    }

    printf("\nPlease enter the values of the 2nd array: ");
    
    for (i = 0; i < N; i  ) {
        if (scanf("%d", &v2[i]) != 1)
            return 1;
    }

    for (i = 0; i < N; i  ) {
        for (j = i   1; j < N; j  ) {
            if (v2[i] > v2[j]) {
                int b = v2[i];
                v2[i] = v2[j];
                v2[j] = b;
            }
        }
    }

    flag = 1;
    for (i = 0; i < N; i  ) {
        if (v[i] != v2[i]) {
            flag = 0;
            break;
        }
    }

    if (flag == 1)
        printf("\nThe arrays have the same numbers! ");
    else
        printf("\nThe arrays dont have the same numbers!");

    return 0;
}

Here is an alternative algorithm with the same time complexity, but without modifying the arrays: for each element of array v, if both arrays have the same number of copies, continue else the arrays are different.

#include <stdio.h>

#define N  100

int count(const int *v, int len, int x) {
    int n = 0;
    for (int i = 0; i < len; i  ) {
        n  = (v[i] == x);
    }
    return n;
}

int main() {
    int v[N];
    int v2[N];
    int i;
    int flag;

    printf("Please enter the values of the 1st array: ");

    for (i = 0; i < N; i  ) {
        if (scanf("%d", &v[i]) != 1)
            return 1;
    }

    printf("\nPlease enter the values of the 2nd array: ");
    
    for (i = 0; i < N; i  ) {
        if (scanf("%d", &v2[i]) != 1)
            return 1;
    }

    flag = 1;
    for (i = 0; i < N; i  ) {
        if (count(v, N, v[i]) != count(v2, N, v[i])) {
            flag = 0;
            break;
        }
    }

    if (flag == 1)
        printf("\nThe arrays have the same numbers! ");
    else
        printf("\nThe arrays dont have the same numbers!");

    return 0;
}

CodePudding user response:

If you need to ensure all elements of the two arrays are the same, but you need to accommodate for them being in different orders, you could either sort them both and compare, or you could keep notes as you go.

You can create an array of ints with the same length as the arrays you're comparing, and use them as flags to check whether you've "used" an index in the second array when checking the elements in the first array.

We'll see this to all 0, then as we scan the first array, we'll disregard any indices in the second array that have already been used. If we find a match, we'll set a flag to say that the index in array 2 has been used, and we'll break the inner loop to save ourselves any further iteration over the second array.

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

int arrays_match(int *arr1, int *arr2, int n) {
    size_t used[n];

    /* Initialize the used array to all 0 or false. */
    for (int i = 0; i < n; i  ) {
        used[i] = 0;    
    }

    for (int i = 0; i < n; i  ) {
        int in_both = 0;

        for (int j = 0; j < n; j  ) {
            if (used[j] == 0 && arr1[i] == arr2[j]) {
                in_both = 1;
                used[j] = 1;
                break;
            }
        }

        if (!in_both) return 0;
    }

    return 1;
}

int main() {
    int a[4] = { 1, 2, 3, 4 };
    int b[4] = { 4, 2, 3, 1 };

    if (arrays_match(a, b, 4)) {
        printf("Huzzah!\n");
    }
    else {
        printf("Huh?\n");
    }
}

This ends up printing "Huzzah!" but if we initialize a with { 4, 2, 2, 1 } then it prints "Huh?"

Consider what happens when we run the below example.

a = { 1, 2, 4, 2 }
b = { 4, 2, 2, 1 }
used = { 0, 0, 0, 0 }

The outer loop deals with a[0] first, which is 1. It iterates through the inner loop until j is 3, at which point it both finds a match, and used[3] is still 0.

a = { 1, 2, 4, 2 }
b = { 4, 2, 2, 1 }
used = { 0, 0, 0, 1 }

Now the outer loop is checking a[1] which is 2. It checks b until it gets to b[1] and used[1] is 0, so it finds a match.

a = { 1, 2, 4, 2 }
b = { 4, 2, 2, 1 }
used = { 0, 1, 0, 1 }

Next the outer loop is checking a[2] which is 4. It checks b until it gets to b[0] and used[0] is 0, so it finds a match.

a = { 1, 2, 4, 2 }
b = { 4, 2, 2, 1 }
used = { 1, 1, 0, 1 }

Finally the outer loop is checking a[3] which is again 2. It checks b until it gets to b[1] which is also 2, but used[1] is 1, so it can't find a match here. It continues on to b[2] and finds a match because used[2] is still 0.

a = { 1, 2, 4, 2 }
b = { 4, 2, 2, 1 }
used = { 1, 1, 1, 1 }

It's reached the end of the iteration and no mismatches have been detected. The function returns 1 (true).

  •  Tags:  
  • c
  • Related