Search code examples
listcomparisonminimization

Match one list into another with minimum error


I have two lists, A and B. A will be at most ~1000 elements, and B will be at most ~100 elements. I want to match every element of B to an element of A, such that the sum of the absolute differences of the pairs is minimized.

i.e. I want to choose |B| distinct indexes from A, and assign them to the indexes of B, such that the following sum is minimized: sum(abs(A[j] - B[i]) for i in |B|, j = index_mapping(i))

My first approach is:

  1. For each element of B, to compute the |B| closest elements of A.
  2. Choose the pairs in a greedy fashion (i.e. minimum error first)

Playing with some simple examples, it's clear that my approach is not the best. It should work fine for my purpose, but I was wondering if anyone could suggest a better approach?


Solution

  • I ended up sorting both lists, and iterating through them to match. This worked well enough for what I was doing.