Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array has any duplicates?

Tags:

arrays

c

I'm reading the contents of file into a 9 element array. I need to check if there are any duplicates in this array. I need to do this without reordering or changing the any of the contents of the array.

How would I go about doing this?

like image 216
Petefic Avatar asked Nov 20 '11 04:11

Petefic


1 Answers

Use brute force.

You've only got 9 elements in the array, so it'll only take 36 comparisons to find any duplicates:

int count = sizeof(array) / sizeof(array[0]);

for (int i = 0; i < count - 1; i++) { // read comment by @nbro
    for (int j = i + 1; j < count; j++) {
        if (array[i] == array[j]) {
            // do whatever you do in case of a duplicate
        }
    }
}
like image 53
Caleb Avatar answered Sep 23 '22 00:09

Caleb