diff --git a/src/permutations.jl b/src/permutations.jl index 9e51ef7..8b39f91 100644 --- a/src/permutations.jl +++ b/src/permutations.jl @@ -170,10 +170,22 @@ function Base.length(c::MultiSetPermutations) return round(Int, p[t+1]) end + +""" + multiset_permutations(a) + +Generate all permutations of an array `a` where `a` may have duplicated elements. +""" +function multiset_permutations(a) + m = unique(collect(a)) + f = [count(==(x), a) for x in m] + multiset_permutations(m, f, length(a)) +end + """ multiset_permutations(a, t) -Generate all permutations of size `t` from an array `a` with possibly duplicated elements. +Generate all permutations of size `t` from an array `a` where `a` may have duplicated elements. """ function multiset_permutations(a, t::Integer) m = unique(collect(a)) diff --git a/test/permutations.jl b/test/permutations.jl index ae18b48..60b5fa9 100644 --- a/test/permutations.jl +++ b/test/permutations.jl @@ -59,6 +59,8 @@ end @test collect(multiset_permutations("aabc", 5)) == Any[] @test collect(multiset_permutations("aabc", 2)) == Any[['a', 'a'], ['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'], ['c', 'a'], ['c', 'b']] + @test collect(multiset_permutations("aabcc", 5)) == collect(multiset_permutations("aabcc")) + @test collect(multiset_permutations("aabc")) == Any[Char[]] @test collect(multiset_permutations("aabc", 0)) == Any[Char[]] @test collect(multiset_permutations("aabc", -1)) == Any[] @test collect(multiset_permutations("", 1)) == Any[]