0

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?
}
7
  • what's the purpose of the array parameter? Commented Sep 9, 2014 at 16:54
  • it specifies the element count of the arrays to be formed Commented Sep 9, 2014 at 16:55
  • then what is arraySize for? Commented Sep 9, 2014 at 16:57
  • the size of the arrays could vary Commented Sep 9, 2014 at 16:57
  • @Carpsen90: In other words, you want all k-element subsets of a given n-element set ? Commented Sep 9, 2014 at 17:10

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.