Puzzle DE47


Check that an array has an element -N for each element N

[M-10] Write a function that checks that each element N of an array is matched by at least one other element with the value -N. There may be several elements with value -N, even if there is just one N. And (also) if there are several values N, they may be matched by just one value -N. If there is one zero in the array, it must be matched by at least one other zero.

Return the number of unmatched values. For example:

   0    1   -6    3    6   -1    8    7   -9    9
   0   -7   -8    8    2    2    6    4    5   -6

5 elements are missing a match.

Here is a testing framework:

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

/* Puzzle D47 -- check that an array has at least one
|                element -N for each element N
|
|  Return the count of the number of elements missing a match,
|  zero or more. If the value zero is in the array, it must
|  be matched with a second zero.
|
|  Note that an array might have more than one -N for a particular N.
*/
int posNegMatch( int size, int arr[] )
{
. . . . 
}

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()
{
  int x[] = { 0, 1, -6, 3, 6, -1, 8, 7, -9, 9,
              0, -7, -8, 8, 2, 2, 6, 4, 5, -6 };

  int SIZE = sizeof(x)/sizeof(int);
  int missing, j ;
  
  printArray( SIZE, x );
  printf("\n\n");
  missing = posNegMatch( SIZE, x );

  if ( missing == 0 )
    printf("No elements are missing a match\n") ;
  else
  {
    printf("%d elements are missing a match.\n", missing);
  }
   
  printf("\n\n");
  return 0;
}



Answer         Next Page         Previous Page Home