본문 바로가기

알고리즘

CyclicRotation_Codility

문제

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).

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

Write a function:

function solution(A, K);

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given

A = [3, 8, 9, 7, 6] K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]

[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]

[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]

 

For another example, given A = [0, 0, 0] K = 1

the function should return [0, 0, 0]

 

Given A = [1, 2, 3, 4] K = 4

the function should return [1, 2, 3, 4]

 

Assume that:

  • N and K are integers within the range [0..100];
  • each element of array A is an integer within the range [−1,000..1,000].

In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.


어떤 배열 A와 숫자 K가 주어졌을 때, K번 회전한 배열을 구하는 문제이다.

 

풀이

function solution(A, K) {
    let arr = A.length == 0 ? [] : A;
    let newArray = [];
    function Loop(arr) {
        let tmp = [];
        tmp.push(arr.pop());

        for (let i = 0; i < arr.length; i++) {
            tmp.push(arr[i]);
        }

        newArray = tmp;
        if ( K-1 > 0) {
            K--; 
            Loop(tmp);
        }
        else { 
            return newArray;
        }
    }

    Loop(arr);

    return newArray;
}

배열의 뒤에서 부터 요소를 꺼내와서 tmp라는 변수에 담고 요소의 나머지 값들을 반복문을 통해 순서대로 담는다.

 

제출하고 나서 다른 사람들의 풀이도 참고하였다.

unshift()을 이용해서 아래와 같이 풀수도 있다.

 

function solution(A, K) {
    let arr = A.length == 0 ? [] : A;
 
    for(let i = 0; i < K; i++) {
        let last = arr.pop();
        arr.unshift(last);
    }
 
    return A;
}

 

또한 k번 회전 숫자가 배열 A길이보다 긴지 짧은지에 따라 아래와 같이 풀어낼 수 있다.

function solution(A, K) {
  const rotationNum = (K > A.length) ? (K % A.length) : K;
  return rotationNum === 0 ? A : [].concat(A.slice(-rotationNum), A.slice(0, A.length - rotationNum));
}

 

출처: Code Playground, 이준생의 하루님의 티스토리

'알고리즘' 카테고리의 다른 글

FrogJmp_codility  (0) 2022.02.18
OddOccurrencesInArray_Codility  (0) 2022.02.16
Remove Nth Node From End of List - leetcode  (0) 2021.11.04
Valid Anagram - leetcode  (0) 2021.10.08
Single Number - XOR 연산자  (0) 2021.09.27