Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/permutations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ julia> collect(multiset_permutations([1,1,2], 3))
"""
function multiset_permutations(a, t::Integer)
m = unique(collect(a))
f = [sum([c == x for c in a]) for x in m]
f = [sum(c == x for c in a)::Int for x in m]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I also removed the square brackets to turn the comprehension into a generator expression, which is ever so slightly more efficient, as can be verified by benchmarking.

Benchmark
julia> a = repeat(1:10, 3);

With comprehension:

julia> @benchmark multiset_permutations($a)
BenchmarkTools.Trial: 10000 samples with 10 evaluations per sample.
 Range (min  max):  1.284 μs   1.236 ms  ┊ GC (min  max):  0.00%  99.62%
 Time  (median):     1.350 μs              ┊ GC (median):     0.00%
 Time  (mean ± σ):   1.921 μs ± 16.533 μs  ┊ GC (mean ± σ):  12.11% ±  1.41%

  ▆█▇▄▂                   ▁   ▁▂ ▁▂▂▁▁▂▃▂▁▂▂▂▁▁▁▁▁           ▁
  █████▇▆▅▅▄▅▇▇▇▅▆▄▅▅▇▆▅▅▇██▇█████████████████████████▇▇▇▇▆▅ █
  1.28 μs      Histogram: log(frequency) by time     3.07 μs <

 Memory estimate: 3.39 KiB, allocs estimate: 55.

With generator expression:

julia> @benchmark multiset_permutations($a)
BenchmarkTools.Trial: 10000 samples with 22 evaluations per sample.
 Range (min  max):  943.545 ns  462.770 μs  ┊ GC (min  max):  0.00%  99.37%
 Time  (median):     976.227 ns               ┊ GC (median):     0.00%
 Time  (mean ± σ):     1.251 μs ±   5.907 μs  ┊ GC (mean ± σ):  13.38% ±  3.54%

  ▇█▄▁   ▁              ▁ ▂▂▁▂▁▂▁▁▁                             ▂
  ████▇▇████▇▆▅▄▃▁▁▁▁▄▆▆█████████████▇▇▆▆▆▄▄▄▄▁▄▄▄▃▅▄▃▃▁▄▄▁▃▁▁▅ █
  944 ns        Histogram: log(frequency) by time       2.54 μs <

 Memory estimate: 2.45 KiB, allocs estimate: 35.

multiset_permutations(m, f, t)
end

Expand Down
1 change: 1 addition & 0 deletions test/permutations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ end
# derangements
@test length(collect(derangements(1:4))) == 9
@test length(collect(derangements(1:8))) == derangement(8) == 14833
@test collect(derangements([])) == [[]]
@test collect(derangements(Int[])) == [Int[]]
@test collect(derangements([1])) == Vector{Int}[]
@test collect(derangements([1, 1])) == Vector{Int}[]
Expand Down
Loading