获取Swift

时间:2018-05-10 02:44:13

标签: 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]

非常感谢!

2 个答案:

答案 0 :(得分:5)

您也可以使用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)

答案 1 :(得分:3)

extension Array {
    var combinations: [[Element]] {
        if count == 0 {
            return [self]
        }
        else {
            let tail = Array(self[1..<endIndex])
            let head = self[0]

            let first = tail.combinations
            let rest = first.map { $0 + [head] }

            return first + rest
        }
    }
}

print([1, 2, 3, 4].combinations)