How to check if an array has any duplicates?

I am reading the contents of a file into an array of 9 elements. I need to check if there are duplicates in this array. I need to do this without changing or changing the contents of the array.

How can I do it?

+7
source share
3 answers

Use brute force.

You have only 9 elements of the array, so only 36 comparisons are required to find 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 } } } 
+13
source

You can use this method:

 // sort a copy of the array with the algorithm you like the most and then... bool duplicates = false; for(i = 0; i < 7; i++) { if (array[i] == array[i+1]) { duplicates = true; break; } } 
-2
source
  int main() { srand(time(0)); int data[10]; for(int c=0;c<=9;c++) { bool found = false; while(!found) { data[c]=rand()%10+1; found=true; for(int r=0;r<c;r++) { if(data[c]==data[r]) found=false; } } } for(int c=0;c<=9;c++) cout << data[c] << endl; return 0; } 
-5
source

All Articles