The Data.Vector
API provides an efficient backpermute
function, which basically applies a index-mapping σ
-vector to a vector v
, i.e. v'[j] = v[σ[j]]
.
Or expressed in list-syntax (for simplicity):
backpermute :: [Int] -> [a] -> [a]
backpermute σ v = map (v !!) σ
Which can have O(n) complexity if !!
has O(1) complexity (which I assume for Data.Vector
). Now I want the inverse "forward" permute
operation (or alternatively a function for inverting the σ
-vector itself), i.e. something like (again in list-syntax):
permute :: [Int] -> [a] -> [a]
permute σ = map snd . sortBy (comparing fst) . zip σ
invperm :: [Int] -> [Int]
invperm σ = permute σ [0..]
Alas, the code above is not O(n) due to sortBy
. But since σ
is assumed to be a permutation of a prefix of [0..]
permute
should be expressible as a O(n) algorithm with the Data.Vector
API.
So, how can I implement an efficient O(n) permute
(or alternatively an O(n) invperm
) in terms of the Data.Vector.*
APIs?
What is the rep() function? In simple terms, rep in R, or the rep() function replicates numeric values, or text, or the values of a vector for a specific number of times.
MARGIN is a variable defining how the function is applied: when MARGIN=1 , it applies over rows, whereas with MARGIN=2 , it works over columns. Note that when you use the construct MARGIN=c(1,2) , it applies to both rows and columns; and. FUN , which is the function that you want to apply to the data.
There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors.
Description. lapply returns a list of the same length as X , each element of which is the result of applying FUN to the corresponding element of X .
Monadic initialization, perhaps?
invSigma :: Vector Int -> Vector Int
invSigma s = create $
do v <- new n
zipWithM_ (write v) s (enumFromN 0 n)
return v
where n = V.length s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With