How to create unique arrays of a given size from an array in Swift?

前端 未结 1 1587
孤城傲影
孤城傲影 2021-01-26 05:32

Given an array of Ints, and a desired array size, myFunction should return an array of all possible unique arrays. All the Ints in the initial array are supposed to

相关标签:
1条回答
  • 2021-01-26 06:22

    If I understand your question correctly then you want to create all k-element subsets of a given set with n elements. This can be done recursively by

    • combining the first element a[1] with all (k-1)-element subsets of the remaining elements a[2] ... a[n], and
    • adding all (k)-element subsets of a[2] ... a[n].

    Swift code (a bit generic so that it can be used not only with integers):

    func allSubsetsOf<T>(elements: [T], withCardinality k : UInt,
        combinedWith prefix : [T] = [], startingWithIndex j : Int = 0) -> [[T]] {
    
            if k == 0 {
                return [prefix]
            }
    
            if j < elements.count  {
                let first = elements[j]
                return allSubsetsOf(elements, withCardinality: k-1, combinedWith: prefix + [first], startingWithIndex : j+1)
                    + allSubsetsOf(elements, withCardinality: k, combinedWith: prefix, startingWithIndex: j+1)
            } else {
                return []
            }
    }
    

    Examples:

    let result1 = allSubsetsOf([1, 2, 3, 4, 5], withCardinality: 3)
    println(result1)
    // [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
    
    let result2 = allSubsetsOf(["a", "b", "c", "d"], withCardinality: 2)
    println(result2)
    // [[a, b], [a, c], [a, d], [b, c], [b, d], [c, d]]
    
    0 讨论(0)
提交回复
热议问题