Search code examples
distributioncollate

Merge two uneven sets of items


I'm trying to get a fairly even distribution of one set of items into another and am looking for an algorithm that can help.

For example, Group A has 42 items and Group B has 16 items. I want to mix both groups together so that B is fairly evenly distributed within A. So, the merged group looks something like: {AA B AAA B AA B AA B AAA.....} It would be easy, of course, if A was a multiple of B, but that is not often the case for my needs.


Solution

  • Well, I've been playing around with this and have come up with a solution that will work for my purposes. I essentially mix the larger items into the smaller items and loop back through until I run out of larger items.

    For Each item In smallerList
      mergedList.add(smallerID)
    Next
    
    itemsRemaining = biggerList.Count
    
    While itemsRemaining > 0
      index = 0
    
      For i = 1 To smallerList.Count
        If index >= mergedList.Count or itemsRemaining = 0 Then Continue While
    
        mergedList.Insert(index , largerID)
        index += 2 + loopCount
        itemsRemaining -= 1
      Next
    
      loopCount += 1
    End While
    

    Then I can replace the IDs with the actual items from the two lists.

    So, for my original example (Group 1 with 42 items and Group 2 with 16), I end up with:

    111 2 111 2 111 2 111 2 111 2 111 2 111 2 111 2 111 2 111 2 11 2 11 2 11 2 11 2 11 2 11 2

    It's a bit front loaded, but for my purposes, this will work out just fine.