Answer DD39

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

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

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

/* Obvious, but slow, solution */
void rotateRightNArray( int size, int arr[], 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( size, arr  );
}

/* Faster Solution */
void rotateRightNArrayV2( int size, int arr[], int N )
{
  int j;
  
  /* Adjust N so that negative shifts are left shifts */
  if ( N<0 )
  {
    N = -N ;
    N = N%size;
    N = size - N;
  }
  else
    N = N%size;

  int temp[N];  /* may not work with your compiler */
   
  /* 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];
    
}

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 );
  /* rotateRightNArrayV2( size, x, shift ); */
  printf("\nRotated Right by %d (version 1): \n", shift); 
  printArray( size, x );
  
  return 0;
}


Back to Puzzle Home