lundi 7 février 2022

Comparing two arrays in C ignoring the order of the elements inside each array

I want to compare two arrays in C, ignoring the order of the elements inside each array, I had two ideas to solve this problem. Well, they're the same, to be honest. The first idea is to make a variable and increment it with 1 if we find our element inside the second table (please see the code below). But this one doesn't work if we give it as an example {3, 2, 2, 1} {1, 2, 3, 4}. the second idea (which I obviously couldn't code) is: setting a variable c=0 for example, after the first loop:

for (i = 0; i < n; i++) {
    c = 0;
    for (...
}

this c will count the number of fails

if (T1[i] != T2[j]) {
    c += 1
}

Then before exiting the j loop, we check if c==n where n is the length of the table. Meaning we have n fails. after that, unsetting cat the beginning of the i loop

this is my code:

#include <stdio.h>

int main() {
    int n, i, j, c = 0;
    printf("give the size of the first array: \n");
    scanf("%d", &n);
    int T1[n];
    int T2[n];
    // remplissage de T1
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table1: ", i + 1);
        scanf("%d", &T1[i]);
    }
    // remplissage de T2
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table2: ", i + 1);
        scanf("%d", &T2[i]);
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (T1[i] == T2[j]) {
                c += 1;
                break;
            }
        }
    }
    if (c == n) {
        printf("True");
    } else {
        printf("False");
    }
}



Aucun commentaire:

Enregistrer un commentaire