Skip to content

Instantly share code, notes, and snippets.

@pavlos-io
Last active January 17, 2020 17:29
Show Gist options
  • Save pavlos-io/824b5bd96270e8958ab38e290459d872 to your computer and use it in GitHub Desktop.
Save pavlos-io/824b5bd96270e8958ab38e290459d872 to your computer and use it in GitHub Desktop.
ostream& operator<<(ostream& os, const vector<int>& v){
os << "[ ";
for(int i = 0; i<=v.size()-1; i++){
os << "'" << v.at(i) << "'";
if(i != v.size()-1) os << ',';
}
os << " ]";
return os;
}
vector<int> rotateA(vector<int> a, int d){
int n = a.size();
if( d == 0 || d == n) return a;
d = d%n;
if(n == 2*d){
// special case when n = 2d, then we just want to swap(i, i+d)
// to avoid an inf. loop
for(int i = 0; i < n/2; i++){
int tmp = a.at(i);
a.at(i) = a.at(i+d);
a.at(i+d) = tmp;
}
}
else{
//in all other cases, start from the end, put elem. into its destination,
// put elem. at dest into its new dest etc.
int i = n-1;
int cycle = n;
int curr = a.at(i);
while(cycle){
int dest = i-d;
if(dest < 0) dest = n+dest;
int tmp = a.at(dest);
a.at(dest) = curr;
i = dest;
curr = tmp;
cycle--;
}
}
return a;
}
int main(){
vector<int> items = {1,2,3,4,5,6};
cout << rotateA(items, 3) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment