Say I have two sets of data, each entry consisting of a weight. Each set is ordered by weight ascending. I'm going to list a couple example sets:
Set 0: {4, 8, 19, 25, 25, 26}
Set 1: {1, 2, 3, 8, 20, 27}
I want to find every possible pair between these two sets, but I want to find those pairs in order of their summed weight from smallest to largest. So 4+1, 4+2, 4+3, 8+1, etc. You can assume the sets are c++ std::multiset
, but beyond that I think it'd be the same in any language.
Now, I thought about having 2 iterators and iterating through starting with the first paired with each second in order, etc but that won't compute each pair in order from smallest summed weight up, since the Set 0: 4
+ Set 1: 8
> Set 0: 8
+ Set 1: 1
, in this example. I could always dump the result into a container that does the sorting for me, but that seems inefficient. I have other optimizations that hinge on being able to do this, as well. Is there a clever way to do this without an extra sort at the end?
edit: I need to get every possible pairing, so it's not as simple as incrementing one iterator or the other to get the smallest sum. That will miss most (half?) of the pairs. Although maybe with an iterator stack of some kind...