Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*O(n)* "forward" Data.Vector `permute` function

Tags:

haskell

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?

like image 687
hvr Avatar asked Jul 18 '11 10:07

hvr


People also ask

What is R rep function?

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.

What is margin in apply function in R?

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.

How do you repeat a value in a vector in R?

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.

Which command applies the function to each element in the given vector and returns a list that contains all the results?

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 .


1 Answers

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
like image 161
Anthony Avatar answered Nov 14 '22 15:11

Anthony