سؤال

This is not exactly packing as I can assign rectangle sizes myself, I just need a packed result. I have rectangles of same ratio and different sizes
FULL,
HALF(area = 1/4 * FULL),
QUARTER(area = 1/4 * HALF).
All will be positioned horizontally only. The container is of width 3 times FULL and height will adjust to fit rectangles.

There will be 150 rectangles which will be given random sizes from array(full,half,quarter). Now I want to arrange these rectangles in the container so that there is no gap.

The container and rectangles are HTML DIVs. I am using JavaScript to pack them.

Here is a fiddle http://jsfiddle.net/MywQ2/1/

In the above code I tried to constrain the selection of next box depending on present one.
May be i am not clear, i will try to explain again. I have 150 boxes, i just want to fill container with 150 boxes, they should be randomly of size full,half,quarter. We can also reject randomly selected size and get another one if it is found to create gap.

هل كانت مفيدة؟

المحلول

I think you either want something impossible or you formulate it wrong. If you pick your rectangles truly random, you will end up with gaps in your container.

In the sample code you have now you pick them semi-random, as it depends on the modulus of status.

If your goals is to fill the container with seemingly random rectangles, maybe next algorithm works for you (peude code):

for rectangle in ['large', 'medium', 'small']:
    try:
        place_rectangle_randomly_in_container(rectangle)
    except NoFreeSpace:
        if rectangle == 'small':
            # container filled
            break

where the place_rectangle_randomly_in_container tries to put the rectangle anywhere in the container at random.

To implement the placement, keep track of the container with a 2-dimensional array of booleans which indicate if that spot is still free; every element in the array represents the space a small rectangle would fill, so if the container can contain 12x12 small rectangles, that would be the dimension of the array. To check if a medium rectangle would fit at [2,3], you need to check the array for [2,3], [2,4], [3,3] and [3,4].

Placing the rectangles is then done by positioning them instead of floating them left.

نصائح أخرى

With the great help from Wesley I was able to find a decent solution to the problem. It exactly is not a packing solution but kind of a solution to produce seemingly random packed boxes without gap. Nothing like optimization was needed for me.

The solution was to divide canvas into 4x4 grids and fill each one 'seemingly random, using a matrix to keep track of vacant positions.

This example fiddle explains it well http://jsfiddle.net/Ua8Cv/ .

(Wesley's solution should be marked as answer, I am writing a separate solution only to help people coming to this page from Google, so have a look at his answer first)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top