Replacing components with indices

KeepLearning
Wed, 24 Apr 2024 00:39:43 +0000
Performance

I am wondering if the following can be done in a better way (without for loop, perhaps): given a vector and a vector of vectors, e.g.

v = [1, 2, 3, 3, 4, 4, 5]
u = [[1,2], [3, 5], [4]]

I like to get

[1, 1, 2, 2, 3, 3, 2]

by mapping the components in v to the indices of u. I came up with two ways as follows:

for i in eachindex(u)
           v[findall(x -> x in u[i], v)] .= i
end

and

cond = Iterators.flatmap(enumerate(u) |> collect) do (i, x) map(reverse, i .=> x) end
for c in cond
           replace!(v, c)
end

The reason why I have a question is that I wonder whether I could do somthing like

for i in eachindex(u)
           replace!(v, u[i] .=> i)
end

, since replace(v, 1=>0) (for example) is possible and I thought of some extension and a possibility of avoiding using a for loop.

13 posts - 5 participants