c++vector

cyclic rotation codility c++ solution


I am trying to solve this problem in Codility...
Here is the code:

 #include <iostream>    
 #include <vector>     
 #include <algorithm>
 using namespace std;

 vector<int> solution(vector<int> &A, int k);
 vector<int> A;   
 A.push_back(3);    
 A.push_back(5);   
 A.push_back(7);   
 A.push_back(9);   
 A.push_back(2);
 int k;
 rotate(A.rbegin(),A.rbegin()+k, A.rend());

While my compiler compiles and run with no problem, codility shows me that "error: 'A' does not name a type". This is the code using to my compiler to check it:

  #include <iostream>
  #include <vector>
  #include <algorithm>
  using namespace std;

  int main()
  {
   vector<int> myVector;
   myVector.push_back(3);
   myVector.push_back(5);
   myVector.push_back(7);
   myVector.push_back(9);
   myVector.push_back(2);
   for(unsigned i=0;i<myVector.size();i++)
   {
     cout<<myVector[i]<<" ";
   }
   cout<<endl;
   int k;
   cout<<"Insert the times of right rotation:";
   cin>>k;
   rotate(myVector.rbegin(),myVector.rbegin()+k, myVector.rend());
   for(unsigned i=0;i<myVector.size();i++)
   {
     cout<<myVector[i]<<" ";
   }
  }

Compiler output:

func.cpp:9:3: error: 'A' does not name a type
   A.push_back(3);
   ^
func.cpp:10:3: error: 'A' does not name a type
   A.push_back(5);
   ^
func.cpp:11:3: error: 'A' does not name a type
   A.push_back(7);
   ^
func.cpp:12:3: error: 'A' does not name a type
   A.push_back(9);
   ^
func.cpp:13:3: error: 'A' does not name a type
   A.push_back(2);
   ^
func.cpp:16:9: error: expected constructor, destructor, or type conversion before '(' token
   rotate(A.rbegin(),A.rbegin()+k, A.rend());
         ^
func.cpp:18:1: error: expected declaration before '}' token
 }
 ^

Detected some errors.

Solution

  • I think you had lot of problem and made some assumption Here is the working code

    1.You don't need to create a new vector as the function has already a referenced vector &A so any change will directly reflect to the original vector

    2.value K is points of rotation which is already input to the function (so no need of cin)

    got it 100% now

    // you can use includes, for example:
    // #include <algorithm>
    
    // you can write to stdout for debugging purposes, e.g.
    // cout << "this is a debug message" << endl;
    #include<algorithm>
    
    
    vector<int> solution(vector<int> &A, int K)
    {
        if (A.empty() || A.size() == 1)
        {
            return A;
        }
        K = K % A.size();
    
        if (K == 0)
        {
            return A;
        }
        std::rotate(A.rbegin(), A.rbegin() + K, A.rend());
        return A;
    }
    

    Output

    enter image description here