Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active June 16, 2021 15:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarketm/21746e1505aa48b60f7116f2092582f6 to your computer and use it in GitHub Desktop.
Save clarketm/21746e1505aa48b60f7116f2092582f6 to your computer and use it in GitHub Desktop.
Cyclic Rotation (JavaScript)
function cyclicRotation(array, times) {
var rotatedArray = array;
while (times > 0) {
var currentArray = rotatedArray.slice();
for (var i = 0; i < currentArray.length; i++) {
rotatedArray[(i+1)%currentArray.length] = currentArray[i];
}
times--;
}
return rotatedArray;
}
console.log(cyclicRotation([], 10)); // []
console.log(cyclicRotation([2,5], 2)); // [2, 5]
console.log(cyclicRotation([2,5,5,5,5,5,5,3,3,2,1,00,6,4], 33)); // [2,1,00,6,4,2,5,5,5,5,5,5,3,3]
console.log(cyclicRotation([1,2,3,4,5,6,7,8,9], 8)); // [2,3,4,5,6,7,8,9, 1]
Copy link

ghost commented Jun 16, 2021

Here's my version

function solution(A, K) {
if (A.length === 0 || K === 0 || K % A.length === 0) return A;
for (let i = 0; i < K; i++) {
let a = A.pop();
A.unshift(a);
}
return A; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment