Puzzle DE45


Fill a third array with the elements two SORTED arrays have in common

[H-15] Write a function that that looks at two sorted arrays and fills a third array with the elements that are common to the first two arrays. This is the same problem as above, except now assume that the two input arrays contain integers in ascending order.

The third array has only one copy of each element in common with the other two arrays. The first two arrays may be of unequal sizes. Return the number of elements in the third array. Here are some sample runs:

Array A:
  -9    1    2    5    5    6    7    8    8    9
  17
Array B:
  -1    1    3    4    5    5    5    9   17   17
  17   18   25

Elements in Common:
   1    5    9   17


Array A:
   2    2    2    2    7   12   12
Array B:
   1    1    1    1    1    1    1    1    1    7

Elements in Common:
   7

Here is a testing framework:

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

/* Puzzle D45 -- fill a third array with the elements
|                two sorted arrays have in common
|
|  Write function that looks at two arrays and fills a
|  third array with the elements that are common to the
|  first two arrays. The first two array are sorted
|  into ascending order.
|
|  The third array has only one copy
|  of each element in common with the other two arrays.
|  The first two arrays may be of unequal sizes.
|  Return the number of elements in the third array.
|
*/
int commonElementsSorted( int arrA[], int sizeA,
                          int arrB[], int sizeB,
                          int out[],  int sizeOut )
{
. . . .
}

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 count ;
  
  int arrA[] = { -5,-3,0,2,4,4,5,5,7,8,9,10,10,10,15};
  int arrB[] = { -10,-5,1,2,2,3,3,5,9,15 };
 
  int sizeA = sizeof( arrA )/sizeof( int );
  int sizeB = sizeof( arrB )/sizeof( int );
  int arrC[sizeA+sizeB];
 
  printf("Array A:\n");
  printArray( sizeA, arrA );
  printf("\nArray B:\n");
  printArray( sizeB, arrB);

  count = commonElementsSorted( arrA, sizeA, arrB, sizeB,
                                arrC, sizeA+sizeB );
  
  printf("\n\nElements in Common:\n");
  printArray( count, arrC );
  
  printf("\n\n");

  return 0;
}



Answer         Next Page         Previous Page Home