Categories
coding solutions

Codility: Cyclic Rotation Solution

Cyclic Rotation

Task

Write a function:

vector<int> solution(vector<int> &A, int K);

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

Solution

You just calculate the previous index of each element and populate the answer accordingly

#include <iostream> using namespace std; #include <cassert> #include <vector> vector<int> solution(vector<int> &A, int K) { std::vector<int>::size_type N = A.size(); vector<int> res(N); for (std::vector<int>::size_type i = 0; i != A.size(); i++) { res[(i + K) % N] = A[i]; } return res; }

Test Function

This code tests the solution
int main() { vector<int> v1{3, 8, 9, 7, 6}; vector<int> vexp1{9, 7, 6, 3, 8}; vector<int> res = solution(v1, 3); for (ulong a = 0; a < res.size(); a++) assert(res[a] == vexp1[a]); vector<int> v2{0, 0, 0}; vector<int> vexp2{0, 0, 0}; res = solution(v2, 1); for (ulong a = 0; a < res.size(); a++) assert(res[a] == vexp2[a]); vector<int> v3{1, 2, 3, 4}; vector<int> vexp3{1, 2, 3, 4}; res = solution(v3, 4); for (ulong a = 0; a < res.size(); a++) assert(res[a] == vexp3[a]); return 0; }

Results

Correctness100%
Performance

Index of solutions to Codility Lessons

One reply on “Codility: Cyclic Rotation Solution”

Leave a Reply

Your email address will not be published. Required fields are marked *