Since you have a length requirement of 16 and assuming that each (i) opportunity in each (b) of the eight blocks is x_i_b in length, you may get some reduction when some cases become impossible.
For example, let's say we have a requirement of length 16, but only 4 blocks, with capabilities with specified lengths
block1: [2,3,4] block2: [5,6,7] block3: [8,9,10] block4: [9,10,11]
Then all possibilities are impossible, since the lengths of block 4 are too long for any combination of blocks 1 to 3 to comprise the rest of 16.
Now, if you have a length, this is really 16, which means that your (possible) lengths range from 1 to 9 if the length is not long.
I see two ways to approach this:
- Greedy
- Dynamic programming
Perhaps even combine them. For the “Greedy” approach, select the largest opportunity in all blocks, then the next largest, etc. Follow this until you pass threshold 16. If you have received all the blocks, you can emit this.
Whether you get the threshold or not, you can iterate over the possibilities.
Dynamic evaluation means that you must save some of the results that you have already calculated. As a choice of some blocks that give you a length of 7, you do not need to re-comment this in the future, but you can iterate over the remaining blocks to see if you can find a combination to give you the tenth of 9.
EDIT . This is similar to a backpack problem, but with an additional restriction of 1 choice per block in each instance. In any case, from the point of view of other optimizations, definitely pre-process blocks only in arrays of lengths and save the current amount at each iteration level. Thus, you should only make 1 amount for each iteration of each cycle, and not 8 amounts for each iteration. Also only str concat if you need to select a selection.
If you don’t need a general solution (perhaps easier if you don’t), you can compose the code with special accelerations of the problem instance by excluding the largest too small combination of lengths (and all choices are shorter than this) and excluding the smallest too large combination of lengths ( and all the choices are bigger).