Solution to Cyclic-Rotation by codility

9 Feb


Question Name: Cyclic-Rotation or CyclicRotation

With Python’s syntactic sugar, the solution is pretty short.

Well, kind of too easy. Let’s try a C++ solution to demo the details better.

Thanks to @micropentium6, the original C++ solution is ugly and bad. Please refer to the solution from @micropentium6. Also another Python solution with the same method as @micropentium6’s can be found in an older post.

33 Replies to “Solution to Cyclic-Rotation by codility

  1. With all due respect, your C++ solution is still like Python tricks. By pushing back, the vector is extended through newly allocated space. You can, actually, do this in place with or without vector.

  2. Javascript Solution

  3. My Javascript solution:

  4. Here is what I came up with for a C# solution. It scored 100% on Codility:

  5. Hello, I am trying to understand your solution and I have to question that I do not find the logic. Please could illustrate me about it or where I can read more details about your code.
    The questions are comment on the solution. Thank you in advances
    def solution(A, K):
    # write your code in Python 2.7
    if len(A) == 0:# why do you equal to cero len(A)?
    return A
    K = K % len(A)# Why do you module K % len(A)
    return A[-K:] + A[:-K]

    • Hello, they are mostly some mathematic issues.
      >> why do you equal to cero len(A)?
      A: handle the special case. Otherwise, when len(A) is 0, “K = K % len(A)” is illegal.
      >> Why do you module K % len(A)
      A: To make sure K is in the range of valid index (between 0 and len(A) – 1). The original question is rotation, so if we increase or decrease K by len(A), the result is totally the same.

  6. My C solution:

  7. My Java solution (100%)

  8. Do we really need to shift array n times ? Instead we only need to figure out what is the index of the array would become the first element of new array, and then copy old array to new array. The following are my java solution.

  9. My Python solution

  10. My soulition in php, got 100%:

    • Hi Ahmed,
      Cannot we use array functions to get the solution?

  11. My C++ solution

  12. My Solution (Python)

  13. My C# Code 100% works

  14. Here is python solution using Reversal Algorithm:

  15. def solution(A, K):
        # write your code in Python 3.6
        x = 1
        while x  0:
            A.insert(0, A[-1])    
            x += 1
  16. This was my answer, for your reference. JS

  17. My VB solution. Bizarre there isn’t a more straightforward way to get array length.

    Analysis summary
    The solution obtained perfect score.

  18. My Python snippet (87%)

Leave a Reply

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

Please put your code into a <pre>YOUR CODE</pre> section. Thanks and Happy Coding!