Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the shuffled indices of two lists/arrays

As a challenge, I've given myself this problem:

Given 2 lists, A, and B, where B is a shuffled version of A, the idea is to figure out the shuffled indices.

For example:

A = [10, 40, 30, 2]
B = [30, 2, 10, 40]

result = [2,   3,    0,      1] 
        A[2]  A[3]   A[0]  A[1]
        ||     ||     ||    ||
        30      2     10    40

Note that ties for identical elements can be resolved arbitrarily.

I've come up with a solution that involves the use of a dictionary to store indices. What other possible solutions does this problem have? A solution using a library also works. Numpy, pandas, anything is fine.

like image 770
cs95 Avatar asked Aug 23 '17 04:08

cs95


1 Answers

We can make use of np.searchsorted with its optional sorter argument -

sidx = np.argsort(B)
out = sidx[np.searchsorted(B,A, sorter=sidx)]

Sample run -

In [19]: A = [10, 40, 30, 2, 40]
    ...: B = [30, 2, 10, 40]
    ...: 

In [20]: sidx = np.argsort(B)

In [21]: sidx[np.searchsorted(B,A, sorter=sidx)]
Out[21]: array([2, 3, 0, 1, 3])
like image 184
Divakar Avatar answered Sep 28 '22 06:09

Divakar