C39 Answer


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

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

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

/* Obvious, but slow, solution */
void rotateRightNArray( int arr[], int size, int N )
{
  int j;
  
  /* Adjust N */
  if ( N<0 )
  {
    N = -N ;
    N = N%size;
    N = size - N;
  }
  else
    N = N%size;
  
  for ( j=0; j<N; j++ )
    rotateRightArray( arr, size );
}

/* Faster Solution, but uses an expensive malloc. */
void rotateRightNArrayV2( int arr[], int size, int N )
{
  int *temp;
  int j;
  
  /* Adjust N */
  if ( N<0 )
  {
    N = -N ;
    N = N%size;
    N = size - N;
  }
  else
    N = N%size;
  
  /* allocate an array for temporary use */
  temp = (int *)malloc( N*sizeof( int ) );
  
  /* copy rightmost N elements to temp array */
  for ( j=0; j<N; j++ )
    temp[j] = arr[size-N+j];
    
  /* shift the array right N positions */  
  for ( j=size-1; j>=N; j-- )
    arr[j] = arr[j-N];
  
  /* copy N rightmost elements to start of array */  
  for ( j=0; j<N; j++ )
    arr[j] = temp[j];
    
  /* return temporary storage */  
  free( temp );
}

void rotateRightArray( int arr[], int size )
{
  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 arr[], int size )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = j;
  }
}

void printArray( int arr[], int size )
{
  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 argc, char *argv[])
{
  const int SIZE = 30;
  int x[ SIZE ];
  int shift = 10;
  
  printf("Original:\n");
  fillArrayInOrder( x, SIZE );
  printArray( x, SIZE );
  printf("\nRotated Right by %d (version 1): \n", shift);
  rotateRightNArray( x, SIZE, shift );
  printArray( x, SIZE );

  fillArrayInOrder( x, SIZE );
  printf("\nRotated Right by %d (version 2): \n", shift);
  rotateRightNArrayV2( x, SIZE, shift );
  printArray( x, SIZE );

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