Answer DB20

#include <stdio.h>
#include <stdlib.h>

/* Puzzle D20 -- determine if two integer arrays are equal
|
|  NOTE: one of these equal methods is wrong. Which one?
|
*/

int equal( int size, int x[], int y[])
{
  int j = 0;
  while ( j<size && x[j] == y[j] )
    j++ ;

  return j==size;
}

int equal2( int size, int x[], int y[])
{
  int j;
  for ( j=0; j<size; j++ )
    if ( x[j] != y[j] ) break;

  return j==size;
}

int equal3( int size, int x[], int y[] )
{
  int j = 0;
  int equalSoFar = 1;

  while ( j<size && equalSoFar )
  {
    if ( x[j] != y[j] )
      equalSoFar = 0;
    else
      j++ ;
  }

  return equalSoFar;
}

int equal4( int size, int x[], int y[] )
{
  int j = 0;

  while( j<size && x[j]==y[j++ ] ) ;

  return j>=size ;
}

void fillArrayInOrder( int size, int arr[], int start )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = j+start;
  }
}

void printArray( int size, int arr[] )
{
  const int N = 10;
  int j;
  
  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

int main()
{
  const int SIZE = 30;
  int x[ SIZE ], y[ SIZE ];
  
  fillArrayInOrder( SIZE, x, 0 );
  fillArrayInOrder( SIZE, y, 0 );
  x[SIZE-1] = -99;

  printf("\nx:\n");
  printArray( SIZE, x );
  printf("\n\ny:\n");
  printArray( SIZE, y );

  if ( equal( SIZE, x, y ) )
    printf("\n\nArrays are equal\n");
  else
    printf("\n\nArrays are NOT equal\n");

  if ( equal2( SIZE, x, y ) )
    printf("\n\nArrays are equal\n");
  else
    printf("\n\nArrays are NOT equal\n");

  if ( equal3( SIZE, x, y ) )
    printf("\n\nArrays are equal\n");
  else
    printf("\n\nArrays are NOT equal\n");

  if ( equal4( SIZE, x, y ) )
    printf("\n\nArrays are equal\n");
  else
    printf("\n\nArrays are NOT equal\n");

  printf("\n\n");
  return 0;
}

Comments: This program implements an equal() method in four different ways. Possibly the first equal() function is the best in terms of clarity, but a case could be made for some of the others. Notice how all functions but the second make use of the short-circuit operation of the && operator.

However, one of the methods is NOT correct. See if you can figure out which one is incorrect without running the program. This might give you some insight into coding clarity.



Back to Puzzle Home