Saturday, 27 July 2019

How to align two lists of numbers

I have two sorted lists of numbers A and B with B being at least as long as A. Say:

A = [1.1, 2.3, 5.6, 5.7, 10.1]
B = [0, 1.9, 2.4, 2.7, 8.4, 9.1, 10.7, 11.8]

I want to associate each number in A with a different number in B but preserving order. For any such mapping we define the total distance to be the sum of the squared distances between mapped numbers.

For example:

If we map 1.1 to 0 0 then 2.3 can be mapped to any number from 1.9 onwards. But if we had mapped 1.1 to 2.7, then 2.3 could only be mapped to a number in B from 8.4 onwards.

Say we map 1.1->0, 2.3->1.9, 5.6->8.4, 5.7->9.1, 10.1->10.7. This is a valid mapping and has distance (1.1^2+0.4^2+2.8^2+3.4^2+0.6^2).

Another example to show a greedy approach will not work:

 A = [1, 2]
 B = [0, 1, 10000]

If we map 1->1 then we have to map 2->10000 which is bad.

The task is to find the valid mapping with minimal total distance.

Is hard to do? I am interested in a method that is fast when the lists are of length a few thousand.



from How to align two lists of numbers

No comments:

Post a Comment