Answer DD40

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

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

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

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

/* Faster, but complicated, solution.   */
void rotateLeftNArrayV2( int size, int arr[], 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;
  
  if ( N==0 ) return;  /* No rotation needed */
  
  /* 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( N, &arr[size-N] );
}

void rotateLeftArray( int size, int arr[] )
{
  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 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()
{
  const int SIZE = 25;
  int shift = 0;
  int x[ SIZE ];
  
  printf("Shift amount-->"); scanf("%d", &shift );
  fillArrayInOrder( SIZE, x );
  printArray( SIZE, x );
  printf("\nRotated Left by %d (version 1): \n", shift);
  rotateLeftNArray( SIZE, x, shift );
  printArray( SIZE, x );

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

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



Back to Puzzle Home