I’m having the requirement, to insert a specific amount of rectangles (which have a defined width but a random height) into another rectangle (which has a defined height and the same defined width as the rectangles to insert). The goal here is, that those inserted rectangles should fill-out the target rectangle as much as possible.
For instance:

I don’t need to get as much rectangles as possible into the black, the goal is to fillout the black rect as much as possible, best case, entirely.
In reality, there are many “black” rectangles and thousands of “reds”, I’m looking for an effective algorithm to calculate. I have to implement this in ECMA-/Javascript so it’s not really the fastest of all platforms.
I looked into some algos like Richard E. Korf’s “Optimal Rectangle Packing” or “Bin packings problems”, but I couldn’t really translate those for this specific problem.
Can somebody recommend me a method/algorithm ?
Because your red and black triangles both have a defined width, you can reduce the problem to a number line, so to speak. Basically, if you ever flipped a red one on its side, you’d most likely end up with wasted space – much more wasted space than putting it in the ‘normal fitting’ way.
So with this in mind, you can reduce the problem exactly to the traditional knapsack problem where the capacity is the height of the black rectangle and the ‘weight’ of the red triangles are their height. The width can be entirely abstracted out of the problem.
Another advantage (as pointed out by xvatar) is that the value density of the candidates are all equal. That is to say that you don’t have the “brick-ring” issue the traditional knapsack problem has. Given the choice between bricks and rings to fill your knapsack with, the rings are obvious candidates. In this case, they’re all the same so there are no obvious candidates.
It would seem the big blocks are easy candidates, but this greedy approach doesn’t fly. Consider the scenario where there are 5 units of space left, and we have bricks of 4, 3 and 2. If we go with the greedy solution, we add the 4, leaving 1 open space. If we would instead have gone with 3 and 2, we would not have the 1 open space remaining.
It also stands to note that once you have identified what rectangles go in, it doesn’t matter what order they go in.
Further reading: http://en.wikipedia.org/wiki/Knapsack_problem