Good algorithm for combining items from N lists into one with balanced distribution?

前端 未结 7 973
北荒
北荒 2020-12-05 20:54

Let\'s say I have the three following lists

A1
A2
A3

B1
B2

C1
C2
C3
C4
C5

I\'d like to combine them into a si

7条回答
  •  感情败类
    2020-12-05 21:42

    First, this answer is more of a train of thought than a concete solution.

    OK, so you have a list of 3 items (A1, A2, A3), where you want A1 to be somewhere in the first 1/3 of the target list, A2 in the second 1/3 of the target list, and A3 in the third 1/3. Likewise you want B1 to be in the first 1/2, etc...

    So you allocate your list of 10 as an array, then start with the list with the most items, in this case C. Calculate the spot where C1 should fall (1.5) Drop C1 in the closest spot, (in this case, either 1 or 2), then calculate where C2 should fall (3.5) and continue the process until there are no more Cs.

    Then go with the list with the second-to-most number of items. In this case, A. Calculate where A1 goes (1.66), so try 2 first. If you already put C1 there, try 1. Do the same for A2 (4.66) and A3 (7.66). Finally, we do list B. B1 should go at 2.5, so try 2 or 3. If both are taken, try 1 and 4 and keep moving radially out until you find an empty spot. Do the same for B2.

    You'll end up with something like this if you pick the lower number:

    C1 A1 C2 A2 C3 B1 C4 A3 C5 B2

    or this if you pick the upper number:

    A1 C1 B1 C2 A2 C3 A3 C4 B2 C5

    This seems to work pretty well for your sample lists, but I don't know how well it will scale to many lists with many items. Try it and let me know how it goes.

提交回复
热议问题