Puzzle DC27


Check if an array contains at least one value x and at least one value y. Return the smallest separation between an x and a y.

[H-25] Write a function that checks that both x and y are in an integer array, but not necessarily one right after the other, and not necessarily in order. Return the number of elements between x and y if they are both there, and -1 if they are not both there. If there are several elements x or y, return the number of elements between the x and y that are closest together.

If both x and y are the same value, then look for two instances of that value in the array. Here is a testing framework:

int distBetweenElts( int size, int arr[], int x, int y )
{
. . . .
}

void printArray( int size, int arr[] );

/* Get user input, x and y. Return 0 if
|  the user wants to quit, otherwise return 1
*/
int userInput( int *x, int *y )
{
  char inputX[32], inputY[32];

  printf("x y: ");
  scanf("%s", inputX );
  
  if ( !isdigit((int)inputX[0]) && inputX[0] != '-' )
    return 0;
  else
  {
    scanf("%s", inputY );
    *x = atoi( inputX );
    *y = atoi( inputY );
    return 1;
  }
}

int main()
{
  const int SIZE = 10;
  int arr[] = { -5, -3, 0, 6, 4, 16, -3, 0, 7, 9 };
  int min, x, y;
   
  printArray( arr, SIZE );
  
  while ( userInput( &x, &y ) )
  {
    min = distBetweenElts(  SIZE, arr, x, y );
    
    if ( min != -1 )
      printf("minimum distance %d\n", min );
    else
      printf("Failed to find both elements.\n");
  }
  	
  return 0;
}

This puzzle is much more difficult than the previous puzzles. Here is sample output of a testing program:

  -5   -3    0    6    4   16   -3    0    7    9
x y: 0 6
minimum distance 0
x y: 0 4
minimum distance 1
x y: 4 0
minimum distance 1
x y: 7 8
Failed to find both elements.
x y: 8 8
Failed to find both elements.
x y: 7 7
Failed to find both elements.
x y: 0 7
minimum distance 0
x y: -3 -3
minimum distance 4
x y: -5 9
minimum distance 8
x y: q


Answer         Next Page         Previous Page Home