简体   繁体   中英

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

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 be unique. An array is considered unique if all its members can't be found in another array.

func myFunction(array : [Int], arraySize : Int) -> [[Int]] {
    //... What to put here?
}

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM