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]
@rowlandekemezie
Copy link

You don't actually need a while loop to get to your solution.

function cyclicRotation(arr, n) {
  const newArr = [];
  for(let i = 0; i < arr.length; i++){
    newArr[(i + n) % (arr.length)] = arr[i]
  }

  return newArr;
}

// TEST
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]

@sivsivsree
Copy link

Can we not use this?

function cyclicRotation(arr, n) {

  for(let i = 0; i < n; i++){
    let a =arr.pop();
     arr.unshift(a);
  }
  return arr;
}

@sererejegede
Copy link

You can add this check before running the code

function cyclicRotation(arr, n) {
  if (n % arr.length === 0) {
    return arr;
  }
  // proceed with logic here
}

@bumsyalao
Copy link

function solution(A, K) {
     let newArr = [];
     newArr = A.splice(K).concat(A.slice(0,K);
     return newArr;
   }

solution([1,2,3,4], 3);

@KAM1310
Copy link

KAM1310 commented Jan 4, 2020

function solution(A, K) { if (!!A.length) { while (K!=0) { K--; A = [A.pop(), ...A]; } return A; } return []; }

@saladinjake
Copy link

saladinjake commented Nov 2, 2020

function solution(A) {

let arr =A;
let dict ={};
let hasIt = arr.filter(function(item,i){
    if(!dict[item]){
         dict[item] =0
        
    }
     dict[item] +=1
    return arr[i]==arr[i+2]
})

for(let [key,val] of Object.entries(dict)){
    if(val ==1){
        return parseInt(key,10)
    }
}

}

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