我正在尝试在 Array 上创建一个扩展,在其中我可以获得一个数组的所有可能组合,而不会生成重复的组,包括无项目组合。
例如,对于这个数组:
[1, 2, 3, 4]
应生成以下可能的组合:
[[], [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]。
这是我能得到的最接近结果:
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]
.
非常感谢!
最佳答案
您也可以使用 flatMap
将它们组合在一行中。
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)
关于arrays - 获取数组中项目的所有可能组合,在 Swift 中没有重复的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50264717/