rohi
rohi

Reputation: 305

How to rotate every Nth element in a vector in c++

I'm trying to rotate every nth element in a vector. I know there is a rotate function in c++ but how can i rotate every nth element?

For example:

([71 65 74 88 63 100 45 35 67 11])-->[65 74 88 71 100 45 35 63 11 67] 

For the above example, if n=4 then rotation should happen at every 4th element.

1st-->([71 65 74 88])-->([65 74 88 71])

2nd-->([63 100 45 35])-->([100 45 35 63])

3rd-->([67 11])-->([11 67])

Upvotes: 3

Views: 533

Answers (2)

KamilCuk
KamilCuk

Reputation: 141200

Just create subranges with specified maximum length from the initial vector using iterators and rotate each one of them.

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

template <class ForwardIterator>
void myrotate_nth (ForwardIterator first, ForwardIterator last,
                   typename std::iterator_traits<ForwardIterator>::difference_type n)
{
    while (last - first > n) {
        ForwardIterator tmp = first + n;
        rotate(first, first + 1, tmp);
        first = tmp;
    }
    rotate(first, first + 1, last);
}

int main()
{
    std::vector<int> v = { 71, 65, 74, 88, 63, 100, 45, 35, 67, 11 };
    myrotate_nth(v.begin(), v.end(), 4);
    for_each(v.begin(), v.end(), [](int c) { cout << c << "\t"; });
    cout << endl;
    return 0;
}

Will output:

65      74      88      71      100     45      35      63      11      67    

Upvotes: 5

selbie
selbie

Reputation: 104559

Simplified version of my original answer. Does the rotation in place.

void RoateEveryNth(vector<int>& vec, size_t n)
{
    if (n <= 1)
    {
        return;
    }

    size_t numChunks = vec.size() / n;
    size_t lastChunkSize = vec.size() % n;

    for (size_t chunk = 0; chunk < numChunks; chunk++)
    {
        size_t offset = chunk * n;
        int firstChunkValue = vec[chunk*n];
        for (size_t i = 1; i < n; i++)
        {
            vec[offset + i - 1] = vec[offset + i];
        }
        vec[offset + n - 1] = firstChunkValue;
    }

    if (lastChunkSize > 1)
    {
        size_t offset = numChunks * n;
        int firstChunkValue = vec[offset];
        for (size_t i = 1; i < lastChunkSize; i++)
        {
            vec[offset + i - 1] = vec[offset + i];
        }
        vec[offset + lastChunkSize - 1] = firstChunkValue;
    }
}

int main()
{
    std::vector<int> vec = { 71, 65, 74, 88, 63, 100, 45, 35, 67, 11 };
    RoateEveryNth(vec, 4);

    for (int i : vec)
    {
        cout << " " << i;
    }
    cout << endl;

    return 0;
}

Upvotes: 1

Related Questions