[Codility/Swift] lesson 2 : CyclicRotation

Task description

  • Notice : N and K can be 0

Solution

To solve this problem, I use another array. The rotate function creates a temporary array, takes the last item of array A first, and then appends each item from array A.

In my first attempt, I missed the cases when K is 0 and N is 0. It's important to check for almost every possible case.

import Foundation
import Glibc

// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")

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

    func rotate(){
        var tmp: [Int] = []   

        tmp.append(A.popLast()!)

        for i in A {
            tmp.append(i)
        }
        A = tmp
    }

    // check is empty
    if A.count == 0 {
        return []
    }

    // Check K is bigger than 0
    if K > 0 {
        var times: Int = K % A.count

        while times > 0 {
            rotate()
            times -= 1
        }
    }


    return A
}