我正在尝试解决以下问题,给定大小为n的String数组,列出该数组中的所有n个元组,即:
PLAY [f5-test] *****************************************************************************
TASK [Add servers to connection pool ] *****************************************************
changed: [f5-test -> localhost]
PLAY RECAP *********************************************************************************
f5-test : ok=1 changed=1 unreachable=0 failed=0
确定所有元组
let A: [String] = ["a","b","c",...]
,其中正好有n!。
我已经用Swift编写了一个解决方案,但是我对结果并不满意,因为它使用了闭包,因此很难遍历元组。
这是代码,以防万一:
["abc..","bac..",...]
有没有封闭的有效解决方案的人吗?
答案 0 :(得分:2)
在“代码查看”中使用Sequence-based enumeration of permutations in lexicographic order中的代码(已针对 Swift 4,并实施了Hamish的答案中的建议):
extension Array where Element: Comparable {
/// Replaces the array by the next permutation of its elements in lexicographic
/// order.
///
/// It uses the "Algorithm L (Lexicographic permutation generation)" from
/// Donald E. Knuth, "GENERATING ALL PERMUTATIONS"
/// http://www-cs-faculty.stanford.edu/~uno/fasc2b.ps.gz
///
/// - Returns: `true` if there was a next permutation, and `false` otherwise
/// (i.e. if the array elements were in descending order).
mutating func permute() -> Bool {
// Nothing to do for empty or single-element arrays:
if count <= 1 {
return false
}
// L2: Find last j such that self[j] < self[j+1]. Terminate if no such j
// exists.
var j = count - 2
while j >= 0 && self[j] >= self[j+1] {
j -= 1
}
if j == -1 {
return false
}
// L3: Find last l such that self[j] < self[l], then exchange elements j and l:
var l = count - 1
while self[j] >= self[l] {
l -= 1
}
self.swapAt(j, l)
// L4: Reverse elements j+1 ... count-1:
var lo = j + 1
var hi = count - 1
while lo < hi {
self.swapAt(lo, hi)
lo += 1
hi -= 1
}
return true
}
}
struct PermutationSequence<Element : Comparable> : Sequence, IteratorProtocol {
private var current: [Element]
private var firstIteration = true
init(startingFrom elements: [Element]) {
self.current = elements
}
init<S : Sequence>(_ elements: S) where S.Iterator.Element == Element {
self.current = elements.sorted()
}
mutating func next() -> [Element]? {
var continueIterating = true
// if it's the first iteration, we avoid doing the permute() and reset the flag.
if firstIteration {
firstIteration = false
} else {
continueIterating = current.permute()
}
// if the array changed (and it isn't the first iteration), then return it,
// else we're at the end of the sequence.
return continueIterating ? current : nil
}
}
一个人可以非常有效地遍历数组的所有排列:
let a = ["a", "b", "c"]
let permSeq = PermutationSequence(startingFrom: a)
for tuple in permSeq {
print(tuple.joined())
}
每次调用迭代器都会创建下一个排列,并且只有一个 需要固定数量的额外存储空间(用于 当前排列和一个布尔变量)。
答案 1 :(得分:0)
我不确定为什么您需要关闭才能生成列表。这是过去使用的内容。使用flatmap可能有1个班轮。
func tuple(_ input:[String])->[String]{
print()
if input.count == 1 {return input}
var output = Array<String>()
for a in 0...input.count-1 {
var temp = input
temp.remove(at: a)
output += tuple(temp).map{input[a]+$0}
}
return output
}
print(tuple(a))