Puzzle DC28


Check if all the integers 0..N-1 are in an array. Return the first integer not found.

[M-7] Write a program that examines an integer array of N elements and determines if all the integers 0..N-1 are in the array. The integers need not be in order. Return the smallest integer in the range 0..N-1 that is not found in the array, or -1 if all integers are there.

   0    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18   19
  20   21   22   23   24   25   26   27   28   29
  30   31   99   33   34   35   36   37   38   39
  40   41   42   43   44   45   46   47   48   49

Element 32 missing

Here is a testing framework:

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

int fullArrayCheck( int size, int arr[] )
{
. . .
}

void fillArrayInOrder( int size, int arr[], int first )
{
  int j;

  for ( j=0; j < size; j++ )
  {
    arr[j] = first+j;
  }
}

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] );    
  }
}

#define SIZE 50
int main()
{
  int x[SIZE] ;
  int target ;
  fillArrayInOrder( SIZE, x, 0 );
  x[ 32 ] = 99 ;
  printArray( SIZE, x );
  printf("\n");

  if ( (target = fullArrayCheck( SIZE, x )) == -1 )
    printf("All elements present\n");
  else
    printf("Element %d missing\n", target);
	
  return 0;
}


Answer         Next Page         Previous Page Home