Like how new recruits in the army are required to do a few pull-ups before lunch, I make myself complete at least 2 Codility challenges a week. If nothing, it helps to keep the mind thinking algorithmically – which I believe is a good thing.
This challenge requires one to cycle through a series of numbers in an array for N times. For example, given the array A = [3,8,9,7,6], to cycle this function once, it becomes A = [6,3,8,9,7]. Notice that the last element becomes the first, and then every other element moves 1 place up.
To cycle it twice, it becomes A = [7,6,3,8,9].
To cycle it thrice, it becomes A = [9,7,6,3,8].
In essence, you are removing the last element, and then moving every element up by 1 place, and then putting the last element back into the first place.
To achieve this, I used 2 loops, one to iterate through every element in the array and moving them up, and another one to do it n times.
Made a mistake in my first attempt because I did not consider the case of an empty array. Total time taken to code: 10 minutes. I have earned my lunch today.
function solution(A, K) {
var holder;
if (A.length != 0){
for (var j = 1; j <= K; j++){
for (var i=A.length-1; i>= 0; i--){
if (i == A.length-1){
holder = A[i];
}
A[i] = A[i-1];
}
A[0] = holder;
}
}
return A;
}
Photo by Charles Koh on Unsplash