问题描述
所以我想编写一个 C++ 程序来执行 r 次数组旋转。现在一次数组旋转意味着数组的第一个元素移动到最后一个位置,第 (i) 个位置的所有其他元素移动到第 (i-1) 个位置。
我面临的问题是,即使我已经为旋转应该发生的次数应用了 forloop,但数组也只旋转了一次。请帮助我解决什么问题。
#include<iostream>
using namespace std;
int main()
{
int i,n,r,arr1[100],arr2[100];
cout<<"Please enter the number of elements in your array: "<<endl;
cin>>n;
cout<<"Please enter the number of rotations to be performed: "<<endl;
cin>>r;
for(i=0;i<n;i++)
{
cin>>arr1[i];
}
for(i=0;i<r;i++)
{
arr2[n-1]=arr1[0];
for(i=1;i<n;i++)
{
arr2[i-1]=arr1[i];
}
}
cout<<"Printing Now:"<<endl;
for(i=0;i<n;i++)
{
cout<<arr2[i]<<"\t";
}
}
解决方法
void Rotate(int arr[],int n,int r){
/* To get the starting point of rotated array */
int mod = r % n;
// Prints the rotated array from start position
for (int i = 0; i < n; i++)
cout << (arr[(mod + i) % n]) << " ";
cout << "\n";
}
试试这个代码。 您可以阅读有关此here
的更多信息 ,对于想要完整工作代码的人:
#include <bits/stdc++.h>
using namespace std;
void leftRotate(int arr[],int k)
{
/* To get the starting point of rotated array */
int mod = k % n;
// Prints the rotated array from start position
for (int i = 0; i < n; i++)
cout << (arr[(mod + i) % n]) << " ";
cout << "\n";
}
int main()
{
int n,k,arr[100];
cout<<"Please enter the number of elements: "<<endl;
cin>>n;
cout<<"Now enter the elements:"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the number of rotations to be performed: "<<endl;
cin>>k;
leftRotate(arr,n,k);
return 0;
}
,
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
ll n,r;
cin>>n>>r;
ll a[n];
/* pre-compute the index where the element would be present after rotation
by 'r' times and then insert it in the array */
for(ll i=0; i<n; i++)
{
ll index = ((n+i)-r)%n;
cin>>a[index];
}
// print the rotated array
for(ll i=0; i<n; i++)
{
cout<<a[i]<<" ";
}
}