-1

I'm trying to implement a rectangle packing algorithm.

I have some rectanges on my input Each rectangle have a heigth and a width(and an index number, so i will be able to identify them when i log them)

I have a matrix (an Integer[][]), and i want to store my rectangles in this matrix. After initialization the matrix cannot be modified, so it has a fixed size.

Let's see and example, where we have two rectangles:

new Rectangle(2,3,1) //height=2, width=3, index=1
new Rectangle(1,2,2) //height=1, width=1, index=2

And let have a 3x3 matrix:

Integer[][] matrix = new Integer[4][3]; //height=4, width=3

After i'm done with running the algorithm, i would like to see something like this (If I print the matrix to system.out):

1 1 1
1 1 1
2 2 0
0 0 0

The first two row stores the 1st rectangle (it's 2 high and 3 wide), and we find the 2nd rectangle in the third row. The 0s mean there are empty spaces left (we could store some other rectangle there as well)

I have trouble finding a good way for a greedy (or any) algorithm.

I sort the rectangles from biggest to smallest. Then i should startsomehow storing the rectangles: if the matrix have enough space, we put it there, if not, we try another cell. we continue on every row and on every cell until we find a place.

Can anyone point me to right direction? A description about a good algorith, pseudo-code, or something i could use to figure my way out.

Thanks, Mark

MarkOOvics
  • 27
  • 2
  • So this is a 2d knapsack problem. https://www.coursera.org/learn/discrete-optimization That course might be helpful. As might this book: http://www.algorist.com/ – TurnipEntropy Nov 10 '16 at 15:58
  • and if we "have and example" then "you an I" will not get it together any way any how- "and let have a 3x3 matrix int[4][3]": it is for laughing you are mixed up!! – gpasch Nov 14 '16 at 21:19

1 Answers1

0

You want to "draw" the rectangles in a matrix, and you have the Rectangles already sorted by size.

You can/should make a cycle that:

  • Gets rectangle sizes (depends, if it's provided by the constructor)
  • Checks if there is enough space in the matrix for the rectangle; 1
  • Draws (use for or while loops to draw).

1 Use matrix[0].length and matrix.length to get the matrix size and compare to the rectangles.

I think the biggest challenge is not to get lost in those variables. You need to keep count on the number of rows that you need to start draw and when to stop and update that variable.