Experiment 2- A left rotation operation on a vector of size N shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,3]. Given a vector of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers. Print a single line of n space-separated integers denoting the final state of the array after performing d left rotations
1. Aim/Overview
of the practical: Array operations
2. Task to be done: A
left rotation operation on a vector of size N shifts each of the array's
elements 1 unit to the left. For example, if 2 left rotations are performed on
array [1,2,3,4,5], then the array would become [3,4,5,1,3]. Given a vector of n
integers and a number, d, perform d left rotations on the array. Then print the
updated array as a single line of space-separated integers. Print a single line
of n space-separated integers denoting the final state of the array after performing
d left rotations
3. Algorithm/Flowchart:
Step 1:Start;
Step 2:Declare Size and
number of rotation.
Step 3:Start a loop until number
of rotation .Inside loop Store first element of Vector.
Step 4:Nest another loop
until (size of vector-1) .
Step 5.Now, Inside this loop
Shift the element of array by one.i.e arr[j]=arr[j+1].
Step 6.At last at arr[j]=first.
Put the element stored at last.
Step 7. Return the rotated
vector.
Step 8.End.
4. Steps for experiment/practical:
#include<iostream>
#include<vector>
using namespace std;
vector<int> rotate(int
d, vector<int> arr) {
int l=arr.size();
int j;
for(int i=0;i<d;i++)
{
int first=arr[0]; // first element
stored 1
for(j=0;j<l-1;j++)
{
arr[j]=arr[j+1]; // 2 3 4 5
}
arr[j]=first; // 2 3 4 5 1
}
return arr;}
int main()
{
vector<int> arr;
cout<<"No of elements :";
int
n;
cin>>n;
cout<<"Number of rotations
:";
int d;
cin>>d;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
arr.push_back(x);
}
arr=rotate(d,arr);
cout<<"array after
rotation"<<endl;
for(int j=0;j<n;j++)
{
cout<<arr[j]<<"
";
}
}
Comments
Post a Comment