Apple Swift - Generate combinations with repetition

后端 未结 5 1937
自闭症患者
自闭症患者 2020-12-28 09:25

I\'m trying to generate a nested array containing all combinations with repetition in Apple\'s Swift programming language.

An detailed explanation of combinations wi

5条回答
  •  心在旅途
    2020-12-28 10:08

    Follow up on the existing answers extending RangeReplaceableCollection to support strings as well:

    extension RangeReplaceableCollection {
        func combinations(of n: Int) -> [SubSequence] {
            guard n > 0 else { return [.init()] }
            guard let first = first else { return [] }
            return combinations(of: n - 1).map { CollectionOfOne(first) + $0 } + dropFirst().combinations(of: n)
        }
        func uniqueCombinations(of n: Int) -> [SubSequence] {
            guard n > 0 else { return [.init()] }
            guard let first = first else { return [] }
            return dropFirst().uniqueCombinations(of: n - 1).map { CollectionOfOne(first) + $0 } + dropFirst().uniqueCombinations(of: n)
        }
    }
    

    [1, 2, 3, 4, 5, 6].uniqueCombinations(of: 2)  // [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 3], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6], [4, 5], [4, 6], [5, 6]]
    
    "abcdef".uniqueCombinations(of: 3) // ["abc", "abd", "abe", "abf", "acd", "ace", "acf", "ade", "adf", "aef", "bcd", "bce", "bcf", "bde", "bdf", "bef", "cde", "cdf", "cef", "def"]
    

提交回复
热议问题