Puzzle DD39


Rotate array elements N positions right

[M-10] Write a function that rotates an integer array right by N positions. If N is negative, rotate N positions left. If N is greater than the size of the array, change N to N%size.

   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

Rotated Right by 10:
  20   21   22   23   24   25   26   27   28   29
   0    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18   19

The easy version — repeatedly rotating right N times — is not efficient. But the other ways of doing this are hard. Write the easy version first so that you can test your efficient version [H-15]against it.

Here is a testing framework (which may not work on all systems because of local array variable x.)

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

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

/* Puzzle C39 -- rotate every array element N positions right */

void rotateRightNArray( int size, int arr[], int N )
{
 
}
 
void rotateRightArray( int size, int arr[] )
{
  int j;
  int lastElt;
  
  lastElt = arr[size-1];
  for ( j=size-1; j>=1; j-- )
      arr[j] = arr[j-1];
      
  arr[0] = lastElt;
}

void fillArrayInOrder( int size, int arr[] )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = 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] );    
  }
}
 
int main()
{
  int size, shift;
  
  /* Gather parameters from user */
  printf("Size of Array: ");
  scanf("%d", &size);
  printf("Amount to rotate: ");
  scanf("%d", &shift);

  /* Create the array (may not work on your system ) */
  int x[ size ];
  fillArrayInOrder( size, x );
  printf("Original:\n");
  printArray( size, x );
  
  /* Shift right and print */
  rotateRightNArray( size, x, shift );
  printf("\nRotated Right by %d (version 1): \n", shift); 
  printArray( size, x );
  
  return 0;
}


Answer         Next Page         Previous Page Home