在Swift中获取数组中所有可能的项目组合而没有重复的组 [英] Get all possible combination of items in array without duplicate groups in Swift
问题描述
我正在尝试在Array上创建扩展,我可以在不生成重复组的情况下获得数组的所有可能组合,包括无项目组合.
I'm trying to create an extension on Array where I can get all possible combinations of an array without generating duplicate groups, including a no item combination.
例如,对于此数组:
[1, 2, 3, 4]
应生成以下可能的组合:
The following possible combinations should be generated:
[[], [1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]
请注意,没有一个组重复自己,即:如果有一个组[1,2],则没有其他组:[2,1].
Please note that none of the groups repeat themselves, i.e: if there is a group [1, 2] there is no other group: [2, 1].
这是我所能获得的最接近的结果:
This is the closest I've been able to get to a result:
public extension Array {
func allPossibleCombinations() -> [[Element]] {
var output: [[Element]] = [[]]
for groupSize in 1...self.count {
for (index1, item1) in self.enumerated() {
var group = [item1]
for (index2, item2) in self.enumerated() {
if group.count < groupSize {
if index2 > index1 {
group.append(item2)
if group.count == groupSize {
output.append(group)
group = [item1]
continue
}
}
} else {
break
}
}
if group.count == groupSize {
output.append(group)
}
}
}
return output
}
}
但是缺少分组大小为3的项目的可能组合(我只得到[1, 2, 3]
和[2, 3, 4]
.
But it is missing possible combination of items in the group size 3 (I only get back [1, 2, 3]
and [2, 3, 4]
.
非常感谢!
推荐答案
您也可以使用flatMap
将它们组合成一行.
You can use flatMap
also to combine them in one line.
extension Array {
var combinationsWithoutRepetition: [[Element]] {
guard !isEmpty else { return [[]] }
return Array(self[1...]).combinationsWithoutRepetition.flatMap { [$0, [self[0]] + $0] }
}
}
print([1,2,3,4].combinationsWithoutRepetition)
这篇关于在Swift中获取数组中所有可能的项目组合而没有重复的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!