Rotating an array A by N position

08 Apr 2019

Given an array A of integers. Write a function to rotate the array by n position;

#include <bits/stdc++.h>
using namespace std;
//function to rotate an array
vector<int> rotateArray(vector<int> A, int n){
	vector<int> ret;
	int s = A.size();
	for(int i = 0; i < s; i++)
		ret.push_back(A[(i + n) % s]);
	return ret;
}
//driver
int main() {
	vector<int> A = {5, 6, 3, 2};
	//before rotation
	for(int i = 0; i < A.size(); i++)
		cout << A[i] << " ";
	cout << endl;
	//rotate by arbitrairy position
	int n = 1;
	A = rotateArray(A, n);
	//after rotation
	for(int i = 0; i < A.size(); i++)
		cout << A[i] << " ";
	return 0;
}