Search code examples
c++data-structuresgeneric-programming

Generic Right Shift


I have been given the following homework question :

Given a set of 'n' elements and 'r', write a generic function to right shift the set of elements by 'r' position. If the elements are to moved to position greater than 'n' then wrap the shift process to the beginning of the collection. For example, if the set of five elements are 1,7,8,9,12 and value of 'r' is 3 then the set of elements would be 8, 9, 12, 1, 7.

I kind of felt a pull towards Circular Queue for this question so I wrote a code using it . Right now it doesn't contain any generic functions but that's not an issue , my problem is that my shift function isn't shifting the elements properly . Please give me a hand with this .

#include<iostream>
#include<string>
using namespace std;
#define max 10

int q[max];
int front,rear;

void init() {
    front = -1;
    rear = -1;
}

void enqueue(int x) {
    if(front == (rear+1)%max) {
        cout<<"Queue overflow";
    }

    if(front == -1) {
        front = 0;
        rear = 0;
    }
    else {
        rear = (rear+1)%max;
    }
    q[rear]=x;
    //cout<<"Front"<<front<<endl;
    //cout<<"Rear"<<rear<<endl;
}

int dequeue() {
    int x;
    if(front == -1) {
        cout<<"Queue Underflow";
    }
    else {
        x = q[rear];
        rear = (rear+1)%max;
    }
    return x;
}

void display() {
    int i;
    if(front == -1) {
        cout<<"Queue Underflow";
    }
    else {
        for(i = front; i != rear; i =( i+1)%max) {
            cout<<q[i]<<'\t';
        }
        cout<<q[rear]<<endl;
    }
}

void shift(int num) {
    //do the shifting business here
    int i,x,r;
    cout<<"Enter by how many positions should the elements be shifted towards the right"<<endl;
    cin>>r;
    for(i = 0; i < (num-r); ++i) {
        x = dequeue();
        enqueue(x);
    }
}

int main() {
    int ch,n,i,x,r;
    init();
    //cout<<"Enter your choice"<<endl;
    //cin>>ch;
    cout<<"Number of elements in the collection"<<endl;
    cin>>n;

    for(i = 0; i < n; ++i) {
        cout<<"Enter the value to be added"<<endl;
        cin>>x;
        enqueue(x);
    }
    cout<<"The elements to be shifted"<<endl;
    display();
    shift(n);
    display();
}

EDIT

The input I have given is :

Number of elements : 5

Elements to be shifted : 1 7 8 9 12

The value by which elements should be shifted : 3

Expected Output :

8 9 12 1 7

Output that I'm getting :

1 7 8 9 12 0 12 0 12


Solution

  • Your bug is in dequeue(). You need to advance the front pointer, not the rear:

    int dequeue() {
        int x;
        if(front == -1) {
            cout<<"Queue Underflow";
        }
        else {
            x = q[front];
            front = (front+1)%max;
        }
        return x;
    }