Last active
October 23, 2023 20:47
-
-
Save JadenGeller/6174b3461a34465791c5 to your computer and use it in GitHub Desktop.
Powerset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array { | |
var powerSet: [[Element]] { | |
guard !isEmpty else { return [[]] } | |
return Array(self[1...]).powerSet.flatMap { [$0, [self[0]] + $0] } | |
} | |
} | |
print([1,2,3,4].powerSet) // -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], [4], [1, 4], [2, 4], [1, 2, 4], [3, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array { | |
var powerSet: [[Element]] { | |
guard !isEmpty else { return [[]] } | |
let tailPowerSet = Array(self[1...]).powerSet | |
return tailPowerSet.map { [self[0]] + $0 } + tailPowerSet | |
} | |
} | |
print([1,2,3,4].powerSet) // -> [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4], [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2], [3, 4], [3], [4], []] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what is complexity of power set algorithm it seems to growth hugely in my case like O(n!) or O(n^k)