【问题标题】:Array Rotations阵列旋转
【发布时间】:2021-05-12 17:49:54
【问题描述】:

所以我想编写一个 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";
}
}

【问题讨论】:

  • 您对所有循环都使用相同的计数器...
  • arr2 仅依赖于未变异的arr1。 (您在循环中执行相同的分配,因此没有额外的更改)。
  • std::rotate 可能会有所帮助。

标签: c++ arrays rotation


【解决方案1】:
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

【讨论】:

  • 希望对您有所帮助!!
【解决方案2】:

对于想要完整工作代码的人:

#include <bits/stdc++.h>
using namespace std;


void leftRotate(int arr[], int n, 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;
}

【讨论】:

    【解决方案3】:
    #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]<<" ";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多