Your function checks if there is a matching pair in the array, and the pair sits together.
Instead of looking for a match, look for a mismatch because while you need all matches to return true, you only need one mismatch to return false:
1 2 3 4 5 6 7 8 9
bool allSame( constunsigned a[], unsigned elements )
{
if(elements <= 1) returntrue;
for(unsigned i = 1; i < elements; i++){
if(a[0] != a[i])
returnfalse;
}
returntrue;
}
Great, thanks! If we want to check all the elements are different, I think we have to check if there is any same pair, function returns to false. so the story is different. How we can check all the elements together.
You could, for each element in the array, iterate over the array again (but start one index past the current) to check that value against everything else.
1 2 3
for(unsigned i = 1; i < elements-1; i++){
for(unsigned j = i + 1; j < elements; ++j){
//...