快速找到字符串数组的所有组合
我有一个字符串数组,我想找到其元素的所有可能组合
I have an Array of String and I want to find all the possible combinations of its element
例如:
Array = [A,B,C,D]
Array = [A,B,C,D]
应产生如下结果:
[A,AB,AC,AD,ABC,ABD,ACD,ABCD,B,BC,BD,BCD,C,CD,D]
[A,AB,AC,AD,ABC,ABD,ACD,ABCD,B,BC,BD,BCD,C,CD,D]
这是我的逻辑:
var array = ["A", "B", "C","D"]
var list = [String]()
for i in 0..<array.count{
let c = array[i]
list.append(c)
var d = c
for count in 1..<array.count{
if i+count < array.count{
for j in i+count..<array.count{
var a = d
a.appendContentsOf(array[j])
print("a : \(a)")
list.append(a)
}
}
d = c
d.appendContentsOf(array[count])
print("d : \(d)")
}
}
print(list.description)
其输出为:
Its Output is :
["A","AB","AC","AD","ABC","ABD","ACD","B","BC","BD","BBD" , "C","CD","D"]
["A", "AB", "AC", "AD", "ABC", "ABD", "ACD", "B", "BC", "BD", "BBD", "C", "CD", "D"]
此输出缺少ABCD,并将BCD错误打印为BBD
This output is missing ABCD and wrongly printed BCD as BBD
任何人都可以通过增强代码或建议您自己的逻辑来帮助我.
Anyone Please Help me in this by Enhancing my code or suggesting your own logic for this.
@yannick 的答案非常接近.
通过计算集合的幂集,可以获得所有可能的子集(包括原始集合和空集合).
By computing a Power Set of your set, you obtain all the possible subsets (including your original set and the empty set).
获得功率集后,您要做的就是将子集连接到单个字符串中,以获得所需的结果.
Once you have obtained the Power Set, all you have to do is join the subsets into a single string in order to obtain the result that you're looking for.
这是完整的解决方案(以及更新的代码和大量注释):
Here's the complete solution (along with updated code and plenty of comments):
extension Array {
var powerset: [[Element]] {
guard count > 0 else {
return [[]]
}
// tail contains the whole array BUT the first element
let tail = Array(self[1..<endIndex])
// head contains only the first element
let head = self[0]
// computing the tail's powerset
let withoutHead = tail.powerset
// mergin the head with the tail's powerset
let withHead = withoutHead.map { $0 + [head] }
// returning the tail's powerset and the just computed withHead array
return withHead + withoutHead
}
}
let myArray = ["A", "B", "C", "D"]
print(myArray.powerset) // -> [["D", "C", "B", "A"], ["C", "B", "A"], ["D", "B", "A"], ["B", "A"], ["D", "C", "A"], ["C", "A"], ["D", "A"], ["A"], ["D", "C", "B"], ["C", "B"], ["D", "B"], ["B"], ["D", "C"], ["C"], ["D"], []]
// joining the subsets
let myResult = myArray.powerset.map { $0.sort().joinWithSeparator("") }
print(myResult) // -> ["A", "AB", "ABC", "ABCD", "ABD", "AC", "ACD", "AD", "B", "BC", "BCD", "BD", "C", "CD", "D", ""]
PS
请注意,此解决方案使用递归方法,而您使用的是迭代方法.
Note that this solution uses a recursive approach, while yours was using an iterative approach.
PPS
如果您不希望在解决方案中使用空字符串""
,则可以将其过滤掉:
If you don't want the empty string ""
in your solution, you can just filter it away:
let myResult = myArray.powerset.map({ $0.sort().joinWithSeparator("") }).filter({ $0 != "" })
print(myResult) // -> ["A", "AB", "ABC", "ABCD", "ABD", "AC", "ACD", "AD", "B", "BC", "BCD", "BD", "C", "CD", "D"]