I'm trying to write the code for a function that Physically rearranges the elements of array a so that all the elements are shifted towards the back by a specified distance. for example if i have an array that is
a[] = {1,2,3,4,5,6}. i give it a distance that i want to rotate the array, like 3. so the rotate function would alter the array making it a[] = {4,5,6,1,2,3}.
here is what i have so far but i cant get it to work just right.
void rotate(int a[], int size, int distance)
{
int n = size;
int d = distance;
int rot = 0;
int nrot = 0;
int* b;
b = newint[n];
for (int i = 0; i< n; i++)
{
b[i] = a[i];
}
for (int i = 0; i < n; i++)
{
while (d > n)
{
d = d - n;
if (d <= n)
break;
}
rot = i + d;
if (rot > n - 1)
{
nrot = d - 1;
nrot = d + nrot;
rot = rot - nrot;
a[rot] = b[i];
}
a[rot] = b[i];
}
}
// using a 2nd array to cache values
void rotate_ex( int a[], int size, int distance )
{
int* b = newint[size];
for( int i = 0; i < size; ++i )
b[(i+distance)%size] = a[i];
for( int i = 0; i < size; ++i )
a[i] = b[i];
delete [] b;// cleanup
}
Maybe if I rewrite it as:
1 2 3 4 5 6 7
void rotate_ex( int a[], int size, int distance )
{
int* b = newint[size];
for( int i = 0; i < size; ++i ) b[(i+distance)%size] = a[i];
for( int i = 0; i < size; ++i ) a[i] = b[i];
delete [] b;// cleanup
}
Other versions I worked out:
1 2 3 4 5 6 7 8 9 10 11 12 13
// rotate "in place" - no 2nd array
void rotate( int a[], int size, int distance )
{
int firstVal = a[0];
for( int i = 0; i < distance; ++i )// for distance number of times
for( int j = 0; j < size; ++j )// rotate one forward
{
int secondVal = a[(j+i+1)%size];
a[(j+i+1)%size] = firstVal;
firstVal = secondVal;
}
}
The recursive one is shortest:
1 2 3 4 5 6 7 8 9 10 11
// recursive - values are cached in the local variables val.
void rotate_rec( int a[], int size, int distance, int i = 0 )
{
int val = a[i];
if( i < size-1 )
rotate_rec( a, size, distance, i+1 );
a[(i+distance)%size] = val;
return;
}