Skip to content

Commit

Permalink
Add powerset function (#63)
Browse files Browse the repository at this point in the history
Fixes #11.
  • Loading branch information
ararslan authored Mar 31, 2018
1 parent 1403f71 commit efa9d0a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/combinations.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export combinations,
CoolLexCombinations,
multiset_combinations,
with_replacement_combinations
with_replacement_combinations,
powerset

#The Combinations iterator

Expand Down Expand Up @@ -261,3 +262,19 @@ function Base.next(c::WithReplacementCombinations, s)
(comb, s)
end
Base.done(c::WithReplacementCombinations, s) = !isempty(s) && s[1] > length(c.a) || c.t < 0

## Power set

"""
powerset(a, min=0, max=length(a))
Generate all subsets of an indexable object `a` including the empty set, with cardinality
bounded by `min` and `max`. Because the number of subsets can be very large, this function
returns an iterator object. Use `collect(powerset(a, min, max))` to get an array of all
subsets.
"""
function powerset(a, min::Integer=0, max::Integer=length(a))
itrs = [combinations(a, k) for k = min:max]
min < 1 && append!(itrs, eltype(a)[])
IterTools.chain(itrs...)
end
6 changes: 6 additions & 0 deletions test/combinations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,9 @@ using Compat.Test
@test_throws DomainError [CoolLexCombinations(5, 0)...]
@test [CoolLexCombinations(4,2)...] == Vector[[1,2], [2,3], [1,3], [2,4], [3,4], [1,4]]
@test isa(start(CoolLexCombinations(1000, 20)), Combinatorics.CoolLexIterState{BigInt})

# Power set
@test collect(powerset([])) == Any[[]]
@test collect(powerset(['a', 'b', 'c'])) == Any[[],['a'],['b'],['c'],['a','b'],['a','c'],['b','c'],['a','b','c']]
@test collect(powerset(['a', 'b', 'c'], 1)) == Any[['a'],['b'],['c'],['a','b'],['a','c'],['b','c'],['a','b','c']]
@test collect(powerset(['a', 'b', 'c'], 1, 2)) == Any[['a'],['b'],['c'],['a','b'],['a','c'],['b','c']]

0 comments on commit efa9d0a

Please sign in to comment.