-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayRotation.cpp
More file actions
95 lines (76 loc) · 1.4 KB
/
Copy pathArrayRotation.cpp
File metadata and controls
95 lines (76 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include<iostream>
#include<algorithm>
/*
Array Rotation by Partition..
*/
using namespace std;
#define M 10000000
int arr[M];
void RotateL(int noOfRotation,int SizeOfArray)
{
noOfRotation%=SizeOfArray;
int noOfSlots = __gcd(SizeOfArray,noOfRotation);
int noOfElements = (SizeOfArray / noOfSlots);
for(int i = 0;i<noOfSlots;i++)
{
int tmp = arr[i];
int j=i;
int k=0;
while(1)
{
/*
As We add nOfRotation to j at some point
it will be > SizeOfArray so take modulus
so that it will around back to valuwe of i.
i.e start index of that slot...
*/
k = (j+noOfRotation)%SizeOfArray;
//break loop as we come to start index of slot.
if(k==i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = tmp;
}
for(int i=0;i<SizeOfArray;i++)
cout<<arr[i]<<" ";
}
void RotateR(int noOfRotation,int SizeOfArray)
{
int noOfSlots = __gcd(SizeOfArray,noOfRotation);
int noOfElements = (SizeOfArray / noOfSlots);
for(int i = 0;i<noOfSlots;i++)
{
int tmp;
int j = i;
int k = (j + noOfRotation)%SizeOfArray;;
while(1)
{
tmp = arr[k];
arr[k] = arr[j];
arr[j] = tmp;
j = k;
k = (j + noOfRotation)%SizeOfArray;
if(k == i)
break;
}
}
for(int i=0;i<SizeOfArray;i++)
cout<<arr[i]<<" ";
}
int main()
{
int T;
int N,R;
cin>>T;
while(T--)
{
cin>>N>>R;
for(int i =0;i<N;i++)
cin>>arr[i];
RotateR(R,N);
cout<<"\n";
}
return 0;
}