I am looking to construct a random permutation of [1, 2, ..., n] along with its inverse using NumPy. In my application, n can be on the order of 100 million so I am looking for a solution that constructs both the permutation and its inverse in minimum time.
What I've tried:
- Computing a random permutation and its inverse separately using inbuilt NumPy functions
p = np.random.permutation(n) pinv = np.argsort(p)
- The same idea as approach 1, but using the solution provided here. I found that this solution can speed up the computation of pinv by an order of magnitude.
def invert_permutation_numpy2(permutation): inv = np.empty_like(permutation) inv[permutation] = np.arange(len(inv), dtype=inv.dtype) return inv p = np.random.permutation(n) pinv = invert_permutation_numpy2(p)
I'm hoping that there is a solution that computes p and pinv jointly and yields additional speedup.