All Same Array

Sep 8, 2013 at 7:32pm
closed account (SwqGNwbp)
Hi, This function only return to true in every case. I want to return to true if all the array elements are same.

1
2
3
4
5
6
7
8
9
10
 bool allSame( const unsigned a[], unsigned elements )
{
	for(unsigned i = 0; i < elements; i++){      
       if(a[i]==a[i+1]){
		   return true;
		   }
	}
return false;

}
Sep 8, 2013 at 7:37pm
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( const unsigned a[], unsigned elements )
{
   if(elements <= 1) return true;
   for(unsigned i = 1; i < elements; i++){      
       if(a[0] != a[i])
         return false;
   }
   return true;
}
Last edited on Sep 8, 2013 at 7:38pm
Sep 8, 2013 at 8:06pm
closed account (SwqGNwbp)
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.
Sep 8, 2013 at 8:13pm
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){
//... 
Last edited on Sep 8, 2013 at 8:13pm
Topic archived. No new replies allowed.