Algorithm

Swift Combination, Permutation

motosw3600 2021. 12. 14. 15:59

Combination

  • 하나의 리스트에서 중복되지 않는 값들을 n개의 조합으로 구함
func combination<T>(_ target: [T], _ count: Int) -> [[T]] {
    var result = [[T]]()
    
    func combi(_ nowTarget: [T], _ index: Int) {
        if nowTarget.count == count {
            result.append(nowTarget)
            return
        }
        for i in index..<target.count {
            combi(nowTarget + [target[i]], i + 1)
        }
    }
    combi([], 0)
    return result
}

combination(["A", "B", "C"], 2)

["A", "B"]
["A", "C"]
["B", "C"]

Permutaion

  • 하나의 리스트에서 중복되는 값들을 n개의 조합으로 구함
func permutation<T>(_ target: [T], _ count: Int) -> [[T]] {
    var result: [[T]] = []
    var visited = Array(repeating: false, count: target.count)
    
    func permutate(_ nowTarget: [T]) {
        if nowTarget.count == count {
            result.append(nowTarget)
            return
        }
        for i in (0..<target.count) {
            if visited[i] {
                continue
            }
            else {
                visited[i] = true
                permutate(nowTarget + [target[i]])
                visited[i] = false
            }
        }
    }
    permutate([])
    
    return result
}

permutation(["A", "B", "C"], 3, 0)

["A", "B", "C"]
["A", "C", "B"]
["B", "A", "C"]
["B", "C", "A"]
["C", "B", "A"]
["C", "A", "B"]

 

참고 출처 : https://developer-p.tistory.com/145

'Algorithm' 카테고리의 다른 글

Merge Sort  (0) 2022.02.16
Dijkstra  (0) 2021.12.28
Floyd Warshall  (0) 2021.12.28
Binary Search  (0) 2021.12.28