0

I'm using codeBlocks (C) and I want to compare two arrays (the have x numbers). Each array is made of grades (numbers, int) for some students, each array represents a class.

I want to compare them and see if both have the same number of students that have the same grade. For example

[75 58 86 75 98] 
[58 75 98 86 75] 

fulfill the purpose while

[75 58 86 75 98] 
[58 86 98 86 75] 

don't because the first class has 75 twice while the second one only has 75 once.

I know how to compare them but I cant check if they fulfill the purpose thanks

for (int i = 0; i < x; i++) {
    for(int j=0; j < x; j++){
        if ( class1 [i] == class2[j]) continue;

    }
}
Jonnus
  • 2,988
  • 2
  • 24
  • 33
Thaer Shamma
  • 5
  • 1
  • 4

2 Answers2

1

You should sort the two arrays first. Once you do that, you can compare them in a single loop retrieving the same array index from each one.

You can use the qsort function to sort each array.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

The best way would probably be to sort them, so that they will meet your requirements if and only if they have the same values at every position (and obviously if they are of the same length, but you can check this even before sorting).

It will look like this (the code is heavily copied from the linked answer)

int comp (const void * elem1, const void * elem2) 
{
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}

and then when you need to do your check:

qsort (class1, sizeof(class1)/sizeof(*class1), sizeof(*class1), comp);
qsort (class2, sizeof(class2)/sizeof(*class2), sizeof(*class2), comp);

for (int i = 0; i < x; i++) {
        if ( class1 [i] != class2[i]) return false; 
}
return true;
Community
  • 1
  • 1
bznein
  • 908
  • 7
  • 21