C40 Answer


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

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

/* Puzzle C40 -- rotate every array element N positions left */

/* Obvious, but slow, solution */
void rotateLeftNArray( 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++ )
    rotateLeftArray( arr, size );
}

/* Fast, but complicated, solution. Does not use malloc.  */
void rotateLeftNArrayV2( int arr[], int size, int N )
{
  int temp;
  int L, R, j, fix;
  
  /* Adjust N */
  if ( N<0 )
  {
    N = -N ;
    N = N%size;
    N = size - N;
  }
  else
    N = N%size;
  
  /* Shift elements left by swapping. */
  for ( L=0; L<size-N; L++ )
  {
    R = L+N;
    temp = arr[ L ];
    arr[ L ] = arr[ R ];
    arr[ R ] = temp ;
  }
  
  /* First N elements now at right, but need rotation */
  fix = N - size%N;
  for ( j=0; j< fix; j++ )
    rotateLeftArray( &arr[size-N], N );
}

void rotateLeftArray( int arr[], int size )
{
  int j;
  int temp;
  
  temp = arr[0];
  for ( j=0; j<size-1; j++ )
      arr[j] = arr[j+1];
      
  arr[size-1] = temp;
}

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 ];
  
  fillArrayInOrder( x, SIZE );
  printArray( x, SIZE );
  printf("\nRotated Left by %d (version 1): \n", shift);
  rotateLeftNArray( x, SIZE, shift );
  printArray( x, SIZE );

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

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