[M-15]
Write a function that moves every element of an array down by
N positions in raster order.
Allow N to be in the range
0 <= N <= NUMROWS*NUMCOLS
.
If N is out of range, do nothing to the array and return 0.
Otherwise, rotate the array and return 1.
Here is an example:
Original: 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 Rotated by 13: 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 0 1 2 3 4 5 6 7 8 9 10 11 12
An easy way to do this is to call the previous function N times.
But for this puzzle,
perform the rotation by moving each element only once.
Think of the array as a 1D sequence of int
s.
Use a local variable inside the function to hold the first N elements,
shift the remaining elements, then copy the first N back to the array.
(Some compilers will not allow this.)
Here is a testing framework:
#include <stdio.h> #include <stdlib.h> int rotate ( int nrows, int ncols, int x[nrows][ncols], int N ) { int temp[N]; /* buffer for the first N elements in row-major order */ int j ; . . . . } void fill2DArray ( int nrows, int ncols, int x[nrows][ncols] ) { int r, c, val = 0; for ( r=0; r<nrows; r++ ) { for ( c=0; c<ncols; c++ ) x[r][c] = val++ ; } } void print2DArray ( int nrows, int ncols, int x[nrows][ncols] ) { int r, c; /* row and column indexes for the array */ /* Print elements in row major order */ for ( r=0; r<nrows; r++ ) { for ( c=0; c<ncols; c++ ) printf("%3d ", x[r][c] ); printf("\n"); } } int tester( int nrows, int ncols, int rot ) { int x[nrows][ncols]; fill2DArray( nrows, ncols, x ); printf("\n\nOriginal:\n"); print2DArray( nrows, ncols, x ); rotate( nrows, ncols, x, rot); printf("\n\nRotated:\n"); print2DArray( nrows, ncols, x ); return 0; } int main(int argc, char *argv[]) { int nrows, ncols, rot; printf("Number of rows: "); scanf("%d", &nrows); printf("Number of cols: "); scanf("%d", &ncols); printf("Rotation: "); scanf("%d", &rot); tester( nrows, ncols, rot ); }