[M-10]
Write a function that rotates an integer array left by N
positions. If N
is negative, rotate N
positions right.
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 Left by 10: 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 0 1 2 3 4 5 6 7 8 9
You can do this puzzle with some small changes to the solutions to D39,
or
see if you can create a completely different way to rotate
[H-15]
.
Here is a testing framework:
#include <stdio.h> #include <stdlib.h> void rotateLeftArray( int size, int arr[] ); /* Puzzle D40 -- rotate every array element N positions left */ void rotateLeftNArray( int size, int arr[], int 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 = 30; int x[ SIZE ]; int shift = 10; 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; }