Combinatorics.jl icon indicating copy to clipboard operation
Combinatorics.jl copied to clipboard

`nthperm!` is not very ergonomic; add 3-arg variant?

Open thchr opened this issue 6 months ago • 0 comments

nthperm!(a, k) overwrites a with the kth permutation. This is difficult to reason about if what one wants is to iterate over k and get the permutations of a without minimal allocations.

For instance, doing something like this is not a good idea:

julia> v = [1, 2, 3]
julia> for k in 1:6
          println(nthperm!(v, k))
       end
[1, 2, 3]
[1, 3, 2]
[3, 1, 2] # <--- 
[1, 2, 3]
[3, 1, 2] # <--- woops, seen this already
[2, 1, 3]

since it returns the same permutations multiple times (because v is being permuted).

I think a three-argument version of nthperm! would be nice. This could just piggy-back off the current 2-argument implementation:

function nthperm!(dst::Vector{T}, a::AbstractVector{T}, k::Integer) where T
     nthperm!(copyto!(dst, a), k)
end

I suppose one could argue it's a trivial function, but it took me a while to realize this would be the right way to integrate with the 2-argument method.

thchr avatar Jun 06 '25 11:06 thchr