0

I need to optimally lay out images with JavaScript on a website page so that the amount of whitespace is minimized.

The optimization problem is basically to minimize the following:

(rightmost x-coordinate of an image - leftmost x-coordinate of an image) +
(bottommost y-coordinate of an image - topmost y-coordinate of an image)

However, no images can be overlapping, so for each image the constraints are:

for i in images
    for j in each other image 
        (topmost coordinate of i > bottommost coordinate of j) || 
        (bottommost coordinate of i < topmost coordinate of j) ||
        (leftmost coordinate of i > rightmost coordinate of j) ||
        (rightmost coordinate of i < leftmost coordinate of j)

In addition, there's a constraint that the rightmost coordinate of any image cannot be greater than the width of the page, and the leftmost coordinate of any image has to be > 0.

First I was thinking of formulating it as a linear programming problem, but all the linear programming libraries I saw for JavaScript don't allow such complex constraints, so I think this may not be a linear problem.

Then I started to think about this as a dynamic programming problem, but I'm not sure how to solve it without trying every combination of layouts, which would be insanely slow.

Does anyone have any idea how to efficiently solve this kind of a problem?

double-beep
  • 5,031
  • 17
  • 33
  • 41
jomak73
  • 137
  • 10

2 Answers2

0

I think you've run into the cutting stock problem which is NP hard. I'm sure the Wikipedia page has references to some heuristic sub optimal solutions that may be better suited for you.

mzedeler
  • 4,177
  • 4
  • 28
  • 41
0

Indeed this cannot be done using pure Linear Programming. However the no-overlap constraints can be formulated using extra binary variables (this will make it a MIP -- Mixed Integer Programming problem) or using constraint programming techniques. Here is an example of these constraints. This presentation Constraint programming in the browser is also interesting.

Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39