Puzzle DE43


Check that two arrays contain only the same elements

[M-5] Write a function who's arguments are two arrays of possibly different sizes. Every element in the first array must also be in the second array, and every element in the second array must be in the first array. However, there may be duplicate elements in either array, and the elements can be in any order.

Return 1 if the conditions are met, 0 otherwise. Here are some sample runs of a testing program:

Array A:
   1    2    3    3    4    5    6    6    7    8

Array B:
   1    2    8    8    3    5    4    6    7    7
   8    8
Arrays have all their elements in common


Array A:
   1    6    6    7    8    2    3    3    4    5

Array B:
   1    2    5    4    6    7    7    8    8    8
   3    8
Arrays have all their elements in common


Array A:
   1    6    6    7    8   99    3    3    4    5

Array B:
   1    2    5    4    6    7    7    8    8    8
   3    8
One array has at least one element not found in the other

Here is a testing framework:

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

int allPresent( int sizeA, int arrA[], int sizeB, int arrB[] );

/* Puzzle D43 -- check that two arrays have all elements in common
|
|   Every element in the first array must also be in the second array,
|   and every element in the second array must be in the first array.
|   However, there may be duplicate elements in either array.
|
|   Return 1 if the conditions are met; 0 otherwise.
|
*/
int allInBoth( int sizeA, int arrA[], int sizeB, int arrB[] )
{
. . . .
}

int allPresent( int sizeA, int arrA[], int sizeB, int arrB[] )
{
  int j, k, current;

  /* check the elements in the first array one by one */
  for ( j=0; j<sizeA; j++ )
  {
    current = arrA[j];

    /* find the first array's element in the second array */
    k = 0;
    while ( k<sizeB && current != arrB[k] )
      k++ ;

    /* return the index of the first element in arrA not in arrB */
    if ( k==sizeB ) return j;
  }

  /* if all the elements in arrA are present in arrB, return -1 */
  return -1;
}

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 loc;
  
  /* Edit the values in these arrays to test your function */   
  int arrA[] = { 1, 2, 3, 4, 5, 6, 7, };
  int arrB[] = { 1, 1, 2, 3, 4, 6, 7, 7};
  
  int sizeA = sizeof( arrA )/sizeof( int );
  int sizeB = sizeof( arrB )/sizeof( int );
 
  printf("Array A:\n");
  printArray( sizeA, arrA );
  printf("\nArray B:\n");
  printArray( sizeB, arrB );

  if ( allInBoth( sizeA, arrA, sizeB, arrB ) )
    printf("\nArrays have all their elements in common\n");
  else
    printf("\nOne array has at least one element not found in the other\n");

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



Answer         Next Page         Previous Page Home