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
}
}
}
sizeof(array) you of course mean sizeof(array) / sizeof(array[0])?count - 1, because otherwise the inner loop at the last iteration is completely useless. I will edit the answer to reflect this improvement.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;
}
}
$ is not a valid character in C's identifiers per the standard, although your compiler may happen to support it. Oh, and you're accessing a non-existing array element, array[9] when i=8.