본문 바로가기
📖 Coding Test/Codility

[Swift] Codility Lesson2 - CyclicRotation

by hyebin (Helia) 2022. 7. 23.

문제

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:

public func solution(_ A : inout [Int], _ K : Int) -> [Int]

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.

 

링크

 

CyclicRotation coding task - Learn to Code - Codility

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

app.codility.com

 

문제 분석

  • 정수 N개로 구성된 배열 A와 정수 K를 입력받는다.
  • 배열 A를 K번 회전시킨 결과를 반환한다.
    • 배열의 회전이란? -  각 요소가 한 인덱스만큼 오른쪽으로 이동되고 배열의 마지막 요소가 첫 번째 위치로 이동됨을 의미
ex) A = [3, 8, 9, 7, 6] K = 3

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

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

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

 

해결방안

  1. 배열이 비어있는지 확인
    • 배열이 비어있다면 빈 배열을 반환
  2. 회전 횟수 K가 N의 배수이거나, 0이라면 배열 A를 그대로 반환 ( N: 배열 A 요소 개수)
    • K가 N의 배수라면 회전하여 다시 원래의 배열로 돌아오기 때문에 계산 없이 원래의 배열로 반환
    • A = [1, 2], K = 4
      • [1, 2] -> [2, 1] -> [1, 2] -> [2, 1] -> [1, 2]
  3. 배열 A의 마지막 요소를 변수에 저장하고, 배열에서 삭제
  4. 배열 A의 0번에 변수에 저장된 값을 삽입
  5. 3,4번 과정을 K번 반복

 

Solution

public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
    if A.isEmpty{
        return []
    }
    else if K % A.count == 0 || K == 0{
        return A
    }
    for _ in 0..<K{
        let num = A.removeLast()
        A.insert(num, at: 0)
    }
    return A
}

반응형

댓글