Rusab Abrez Asher Rusab Abrez Asher - 1 month ago 8
C Question

Comparison of one element in array to all other elements in same array

I understand that we can compare each element of the array with every other in this manner:

for (f = 0; f < length2; f++) {
for (p = f + 1; p < length2 ; p++) {
if(!(compareThem(split[f],split[p]) == 1) && (split[f] != 0) && (split[p] != 0)) {
no_of_unique++;
}
}
}


However, I only want no_of_unique to increase after checking the element of index f with ALL the element of index p. This, however, checks the element f with p= f + 1, increases no_of_unique, then checks the other elements and increases it for each case. I only need it to increase after its checked ALL of the elements. Any help would be appreciated.

P.S The compareThem function basically just returns 1 if they are equal to one another.

Answer

Instead of incrementing no_of_unique within the scope of the inner loop, you may simply break after finding an element that is equal to split[f]. Then, outside the inner loop, you should check whether p is equal to length2, which would mean that the inner loop did not break and traversed all the elements till the end of the array. (i.e. did not encounter an element equal to split[f])

for (f = 0; f < length2; f++) {
    if (split[f] != 0) {
        for (p = f + 1; p < length2 ; p++) {
            if( (split[p] != 0) && (compareThem(split[f],split[p]) == 1)) {
                break;
            }
        }
        if (p == length2) {
            no_of_unique++;
        }
    }
}
Comments