An array ‘A’ consisting of ‘N’ integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).

CyclicRotation coding task - Learn to Code - Codility

solution

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

So we need to make a function that has two arguments like this. def solution(A,K)

First of all, we need a new array that already shifted each element, and after that repeats this process. There is a common way to repeat some method, it is for loop.

def solution(A , K):
     # define A as an old version array
		 old = A
		 # make a new array has a same length
     new = [0]*len(A)
		 # for loop iterated 'K' times
     for i in range(K):

Inside of for literation, move the last element of the old version array to the first element of the new one. And the rest of the elements is saved into the new array index 1. After all ‘new’ array should be changed into the ‘old’ version array for the next iteration.

def solution(A , K):
     # define A as an old version array
		 old = A
		 # make a new array has a same length
     new = [0]*len(A)
		 # for loop iterated 'K' times
     for i in range(K):
					# shift the last element to the first place.
				  new[0] = old[-1]
					# rest of elements moved after index 1.
					new[1:] = old[:-1]
					# copy new array into old array
					old = new.copy()

If we do not use copy(), output of function would be changed. Let me check this.

def solution(A , K):
     old = A
     new = [0]*len(A)
     for i in range(K):
         new[0]=old[-1]
         print(new[0])
         print(new, new[1:])
         new[1:] = old[:-1]
         print(new[1:])
         old = new.copy()
         print(old)
     return new

print(solution([1,2,3,4,5], 2))

To check the meaning of copy(), put in the print() each steps.

cyclicRotation1.png

cyclicRotation2.png

This is an immutability issue. If we use not copy(), an old array will be the same as the new array when got an [-1] index element. So we need to keep immutability between the old and new arrays after doing the first iteration.

Reference

https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/