scheinerman / Permutations.jl

Permutations class for Julia.
Other
51 stars 14 forks source link

Feature request: efficiently permute a vector #26

Closed LilithHafner closed 2 years ago

LilithHafner commented 2 years ago

That is, compile a permutation to something that can be efficiently applied to multiple vectors (e.g. cycle annotation). For example,

# permute a vector `v` based on a permutation `p` listed in cycle notation
function cycle_permute!(v::AbstractVector, cycles::AbstractVector{<:AbstractVector})
    for cycle in cycles
        fst = v[first(cycle)]
        for i in firstindex(cycle):lastindex(cycle)-1
            v[cycle[i]] = v[cycle[i+1]]
        end
        v[last(cycle)] = fst
    end
    v
end

Is a decent bit faster than Base.permute!.

scheinerman commented 2 years ago

@LilithHafner : Thank you for your various suggestions. I'm not sure when I'm going to be able to look carefully at these (traveling this past weekend and an overfull week ahead) but I will try to soon.

LilithHafner commented 2 years ago

There's no hurry. If you decide to add this, I've got a sample implementation headed to DataFrames.