arrays - 获取数组中项目的所有可能组合,在 Swift 中没有重复的组

标签 arrays swift math grouping

我正在尝试在 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/

相关文章:

php - 必须插入varchar时如何将数组插入MySQL

c# - 在 C# 中使用 System.IO.File.ReadAllLines(fil) 跳过第一行

swift - 打开一个不是 Root View 的 View ,并将 tabbarcontroller 保留在 Root View 中(swift)

swift - 在 Swift 的元组中是否可以有一个 nil 值?

java - 整数除法

javascript - 如何根据数组属性的索引拆分和合并javascript对象

c - 如何生成随机的 0 和 1 但它们在 C 中出现的概率为 80-20?

multithreading - 如何在 Swift 中创建 volatile bool 值?

math - 这个基本卷积是在普通卷积神经网络中进行的吗?

Java 数学练习未给出正确答案