본문 바로가기

코딩 테스트/Codility

Codility CyclicRotation JavaScript 풀이

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

 

CyclicRotation coding task - Learn to Code - Codility

Rotate an array to the right by a given number of steps.

app.codility.com

내가 실제로 제출한 코드는 아래와 같다.

function solution(A, K) {
    // write your code in JavaScript (Node.js 8.9.4)
    if (!A || A.length === 0) return A;
    for (var i = 0 ; i < K ; i++) {
        A.unshift(A.pop());
    }
    return A;
}

 

테스트 케이스에 A = undefined 등의 falsely 값이나 빈 배열이 있을 경우를 대비해 두 경우에는 A를 그대로 리턴했다.

반복문 안에서는 unshift와 pop을 사용했다. shift와 push를 사용한다면 다른 로직으로 응용할 수 있을 것이다.

 

스코어는 100을 기록했지만 쉬운 문제였다.