如何从在夫特阵列创建一个给定大小的独特阵列? [英] How to create unique arrays of a given size from an array in Swift?
问题描述
由于int数组,而所需的数组大小, myFunction的
应返回所有可能的唯一一个数组的数组。最初的数组中的所有整型都应该是独一无二的。数组被认为是独一无二的,如果它的所有成员不能在另一个数组中找到。
FUNC myFunction的(数组:[INT],ARRAYSIZE为:int) - GT; [INT]] {
// ...怎么放在这里?
}
如果我理解你的问题正确,那么你想创建所有的k元
一组给定有n个元素的子集。这可以通过递归
- 相结合的第一个元素
A [1]
所有(K-1)-element的子集
剩余的元素A [2] ...... A [N]
和 - 添加所有(K)
的-element一个子集[2] ...... A [N]
。
雨燕code(有点的通用的,这样它可以用来不仅整数):
FUNC allSubsetsOf< T>(元素:[T],withCardinality K:UINT,
combinedWith preFIX:[T] = [],startingWithIndex记者:INT = 0) - > [[T]] { 如果k == 0 {
返回[preFIX]
} 如果J< elements.count {
让第一要素= [J]。
返回allSubsetsOf(元素,withCardinality:K-1,combinedWith:preFIX + [首页],startingWithIndex:J + 1)
+ allSubsetsOf(元素,withCardinality:K,combinedWith:preFIX,startingWithIndex:J + 1)
}其他{
返回[]
}
}
例如:
让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]让结果2 = allSubsetsOf([一,B,C,D],withCardinality:2)
的println(结果2)
// [[A,B],[A,C],[A,D],[B,C],[B,D],[C,D]]
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 elementsa[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]]
这篇关于如何从在夫特阵列创建一个给定大小的独特阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!