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?
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?
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
        }
    }
}
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;
   }
}
 
    
     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;
}