Algorithm

배열을 이용한 알고리즘

GREEN.1229 2021. 6. 28. 12:12

아래 문제는 코딜리티에서 제공하는 CyclicRotation의 문제입니다🧑🏻‍💻

문제 제시

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.

Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

문제 해결

import Foundation
import Glibc

public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
    var count = K
    var arr = A
    
    if arr.isEmpty {
        return arr
    }
    
    while count != 0 {
        let temp = arr.removeLast()
        arr.insert(temp, at: 0)
        count -= 1
    }
    
    return arr
}

사용된 개념

 - 배열

 - 조건문 / 반복문

 - 배열요소 삭제 및 추가

문제 뒷담화

해당 문제는 비교적 배열을 쉽게 다룰 수 있다면 간단한 문제였다.

배열의 마지막 요소를 첫요소로 K번 만큼 이동 시킨 후 마지막 배열을 반환해주는 문제이다.

우선 배열이 비어있을 경우에는 바로 해당 배열을 리턴하게끔 조건문을 구성하였다.

해당 조건문이 없다면 빈 배열에 대해 런타임 에러가 난다.

그 후 while 조건문을 사용해 K를 담은 카운트 변수가 0이면 돌지 않고 0이 아니라면 조건문을 돌도록 하였다.

조건문은 배열의 마지막 요소를 삭제하고 해당 변수를 temp 변수에 담는다.

그 후 배열의 첫 요소에 temp 변수를 추가해주고 count 변수값을 1씩 감소시킨다.

마지막으로 배열을 리턴하면 아래와 같이 100프로의 TC 통과율을 보여준다.

[참고자료]

https://app.codility.com/c/run/trainingUFZTXP-KZA/

 

Codility

Your browser is not supported You should use a supported browser. Read more

app.codility.com