Home > Enterprise >  Circular Array C move to right
Circular Array C move to right

Time:11-22

#include <iostream>
using namespace std;
void circularShift(int *vec, unsigned int shift);
int main()
{
    int vec[5] = { 0, 1, 5, 3, 4 };
    circularShift (vec, 4);
    return 0;
}
void circularShift (int *vec, unsigned int shift)
{
    int B[5];
    for (int i = 0; i<5;i  )
    {
        B[(i shift)%5]=vec[i];
    }
    for(int i =0; i<5;i  )
    {
        cout<< B[i];
    }
}

I have this output 15340 in B and I want 40153. and later save this value to vec. Final output vec = 40153. Any idea about the solution

CodePudding user response:

First of all, apply one of the most important programming rules: Single Responsibility Principle

Your shift function also prints the output. That should be done by a different function.

Also, observe, that shifting left can always be done by shifting right. Shifting left by $k$ steps is the same as shifting right by n-k steps.

Among other improvements, this is the working code. Make sure to not blindly copy it, but to be able to understand it and ask questions if something is unclear.

#include <iostream>
#include <vector>

using std::cout;
using std::size_t;
using std::vector;

vector<int> circular_shift_left( vector<int> const& vec, size_t shift )
{
    const size_t N = vec.size();
    vector<int> result(N);
    for( size_t i = 0; i < N;   i )
    {
        result[i] = vec[(i   shift) % N];
    }
    return result;
}

vector<int> circular_shift_right( vector<int> const& vec, size_t shift )
{
    return circular_shift_left(vec, (vec.size()-shift));
}

void print_vector( vector<int> const& vec )
{
    for( auto const& elem : vec )
    {
        std::cout << elem << " ";
    }
}


int main()
{
    vector<int> vec = { 0, 1, 5, 3, 4 };
    auto shifted_l = circular_shift_left(vec, 4);
    auto shifted_r = circular_shift_right(vec, 4);
    print_vector(shifted_l);
    cout << "\n";
    print_vector(shifted_r);
    return 0;
}

CodePudding user response:

In addition to method by infinitzero, you may consider designing data structure for your circular list to prevent unnecessary copy/move.

A simple implementation with only rotate method:

template<typename T>
class CircularVector {
public:
    CircularVector() {}
    CircularVector(std::initializer_list<T> l) : data_(l) {}

    void rotate(int diff) {
        idx = (idx   diff) % data_.size();
    }

    auto print() const {
        for (int i = 0; i < data_.size(); i  ) {
            std::cout << data_[(i   idx) % data_.size()] << " ";
        }
        std::cout << "\n";
    }

private:
    std::vector<T> data_;
    size_t idx = 0;
};

int main() {
    CircularVector<int> arr = {1, 2, 3};
    arr.print();

    arr.rotate(2);
    arr.print();
    
    arr.rotate(-1);
    arr.print();
}
  • Related