Skip to content

Should we use a polyalg for permute!? #58865

@araujoms

Description

@araujoms

permute!(v, p) is strictly worse than v[p]. It is slower, allocates more memory, and doesn't work for multidimensional arrays. It shouldn't exist. I think the following alternatives are reasonable:

  1. Deprecate it.
  2. Write instead something like
function permute!(v::AbstractArray, p::AbstractArray)
    for i in 1:length(p)-1
        ind = p[i]
        while (ind < i)
            ind = p[ind]
        end
        if i != ind
            temp = v[i]
            v[i] = v[ind]
            v[ind] = temp
        end
    end
    return v
end

This is much slower but at least it doesn't allocate. EDIT: Copied correct in-place algorithm from StackOverflow.
3. Define permute!(dest, src, p) = @views dest .= src[p], which is faster and doesn't allocate.

I'm happy to do a PR for any of the alternatives if there's agreement. Not also that invpermute! suffers from similar problems.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions