ielyamani
ielyamani

Reputation: 18581

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?
}

Upvotes: 0

Views: 164

Answers (1)

Martin R
Martin R

Reputation: 539685

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

Upvotes: 1

Related Questions