Good evening, people!
I’m trying to solve a rather simple problem, but.. well, it seems that I can’t. 🙂
The idea is that I have a FIFO list (FIFO queue) with n elements and it’s given a value, k (k < n). My little program has to move the elements to the left with k elements. (e.g. for n=4, k=3, a[]=(1, 2, 3, 4), the result is 4 1 2 3).
But well, I get nowhere near that.
This is what I’ve written so far:
#include <iostream>
using namespace std;
void move (int a[100], unsigned n, unsigned k) {
int t[100];
unsigned i;
for (i=0; i<=n-1; i++) t[i]=a[i];
for (i=0; i<=k-1; i++) a[i]=a[i+k-1];
for (i=k; i<=n-1; i++) a[i]=t[i+1];
}
int main () {
int a[100];
unsigned k, n, i;
cout<<"n; k= "; cin>>n>>k;
for (i=0; i<=n-1; i++) cin>>a[i];
move (a, n, k);
for (i=0; i<=n-1; i++) cout<<a[i]<<" ";
}
Any help would be greatly appreciated. Thank you in advance.
I’m not sure if I’ve understood your question completely. But looks like you effectively want to rotate the contents of the array.
To rotate the array contents to the left k times. You can do the following:
Example:
[3 2 1 4 5]
elements: [3 2 1 5 4]
5 1 2 3]
C++ function to do the same:
A better way to do it in constant space is to do the reversal in-place: