Codility with Swift

Panther·2021년 9월 17일
0

Algorithm Practice

목록 보기
2/3
post-custom-banner

Lesson 1: Iterations


BinaryGap

문제 출처: https://app.codility.com/programmers/lessons/1-iterations/binary_gap/start/

public func solution(_ N : Int) -> Int {
    
    var binaryString = ""
    var temp = N
    
    while temp != 0 {
        binaryString += String(temp % 2)
        temp = temp / 2
    }

    var arr = binaryString.components(separatedBy: "1")

    if binaryString.first == "0" {
        arr.removeFirst()
    } else if binaryString.last == "0" {
        arr.removeLast()
    }

    var result = 0

    for i in arr {
        result = max(result, i.count)
    }

    return result

}

Lesson 2: Arrays


CyclicRotation

문제 출처: https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/start/

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

    if A.isEmpty {
        return []
    } else {
        rotationCount = K % A.count
    }
    
    if A.count == 1 {
        return A
    } else if rotationCount == 0 {
        return A
    } else {
        for _ in 1...rotationCount {
            A.insert(A.removeLast(), at: 0)
        }
    }
    
    return A
    
}

OddOccurrencesInArray

문제 출처: https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/start/

public func solution(_ A : inout [Int]) -> Int {
    
    var result = Int()
    var dict = [Int:Int]()

    for i in 0..<A.count {
        dict[A[i], default: 0] += 1
    }

    for (key, value) in dict {
        if value % 2 == 1 {
            result = key
        }
    }
    
    return result
    
}

Lesson 3: Time Complexity


FrogJmp

문제 출처: https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/start/

public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
    
    let distance = Y - X

    if distance % D > 0 {
        return distance / D + 1
    } else if distance % D == 0 {
        return distance / D
    } else {
        return distance / D + 1
    }

}

PermMissingElem

문제 출처: https://app.codility.com/programmers/lessons/3-time_complexity/perm_missing_elem/start/

public func solution(_ A : inout [Int]) -> Int {
    let totalSum = A.reduce(0) { $0 + $1 }
    var expectedSum = 0

    for i in 0..<A.count + 1 {
        expectedSum += i + 1
    }

    return expectedSum - totalSum
}

Exercise 7: Data Structures


문제 출처: https://app.codility.com/programmers/trainings/7/arr_list_len/start/

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

    var index = 0
    var count = 0

    while A[index] != -1 {
        index = A[index]
        count += 1
    }

    if A.isEmpty {
        return 0
    } else {
        return count + 1
    }
    
}
post-custom-banner

5개의 댓글

comment-user-thumbnail
2023년 6월 18일

xcbxcbxcb

답글 달기
comment-user-thumbnail
2023년 6월 18일
답글 달기
comment-user-thumbnail
2023년 6월 18일
답글 달기
comment-user-thumbnail
2023년 6월 18일
답글 달기
comment-user-thumbnail
2023년 6월 18일
답글 달기