Skip to content

Commit efa9d0a

Browse files
authored
Add powerset function (#63)
Fixes #11.
1 parent 1403f71 commit efa9d0a

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/combinations.jl

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
export combinations,
22
CoolLexCombinations,
33
multiset_combinations,
4-
with_replacement_combinations
4+
with_replacement_combinations,
5+
powerset
56

67
#The Combinations iterator
78

@@ -261,3 +262,19 @@ function Base.next(c::WithReplacementCombinations, s)
261262
(comb, s)
262263
end
263264
Base.done(c::WithReplacementCombinations, s) = !isempty(s) && s[1] > length(c.a) || c.t < 0
265+
266+
## Power set
267+
268+
"""
269+
powerset(a, min=0, max=length(a))
270+
271+
Generate all subsets of an indexable object `a` including the empty set, with cardinality
272+
bounded by `min` and `max`. Because the number of subsets can be very large, this function
273+
returns an iterator object. Use `collect(powerset(a, min, max))` to get an array of all
274+
subsets.
275+
"""
276+
function powerset(a, min::Integer=0, max::Integer=length(a))
277+
itrs = [combinations(a, k) for k = min:max]
278+
min < 1 && append!(itrs, eltype(a)[])
279+
IterTools.chain(itrs...)
280+
end

test/combinations.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,9 @@ using Compat.Test
3939
@test_throws DomainError [CoolLexCombinations(5, 0)...]
4040
@test [CoolLexCombinations(4,2)...] == Vector[[1,2], [2,3], [1,3], [2,4], [3,4], [1,4]]
4141
@test isa(start(CoolLexCombinations(1000, 20)), Combinatorics.CoolLexIterState{BigInt})
42+
43+
# Power set
44+
@test collect(powerset([])) == Any[[]]
45+
@test collect(powerset(['a', 'b', 'c'])) == Any[[],['a'],['b'],['c'],['a','b'],['a','c'],['b','c'],['a','b','c']]
46+
@test collect(powerset(['a', 'b', 'c'], 1)) == Any[['a'],['b'],['c'],['a','b'],['a','c'],['b','c'],['a','b','c']]
47+
@test collect(powerset(['a', 'b', 'c'], 1, 2)) == Any[['a'],['b'],['c'],['a','b'],['a','c'],['b','c']]

0 commit comments

Comments
 (0)