Sort squares in 2d | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Sort squares in 2d

if we have squares with diferent sizes (5x20, 13x18, 10x7...,), how can we stack them into a big square to use the less space possible - so to fill the most gaps. I was thinking to draw a square aruound them and mix the until the outside square is smalest. Its kinda challenging..

11th Dec 2018, 5:32 AM
Varadi Nikica {🧙}
Varadi Nikica {🧙} - avatar
5 Answers
+ 6
I ended up playing with it. Wasn't as bad as I guessed. Sorting by area so biggest is first and putting the first in (0, 0) leaves only two choices bottom left or top right for the next. Each placement removes one location and adds two new ones (though my code doesn't bother with the removal.) https://code.sololearn.com/c3W8PUt77gG6
9th Feb 2019, 10:27 AM
John Wells
John Wells - avatar
+ 4
It does sound challenging so I might attempt it at some point. I'd add the heights together for the maximum needed. Do the same for the widths. That gives the worst case scenario rectangle. Then, use a recursive algorithm trying various placements of each square in that rectangle to minimize the used space. The algorithm has 12 possible placements of a square off each currently placed squares (4 corners times 3 available spots of: up-left, up, up-right, left, right, down-left, down, & down-right). The square must be completely in the worst case rectangle to be valid without overlap of placed squares. The algorithm must try all remaining squares in each of their possible placements. For each try, it recursives until all squares are placed. Once they are all placed, calculate the enclosing rectangle size keeping the minimum with it's square placements.
12th Dec 2018, 7:02 PM
John Wells
John Wells - avatar
+ 4
If you end up doing it, post it here as I made a challenge out of it. https://www.sololearn.com/post/65539
9th Feb 2019, 12:09 PM
John Wells
John Wells - avatar
+ 3
wow. I like that. I like the way of visualisation as well !
9th Feb 2019, 10:37 AM
Varadi Nikica {🧙}
Varadi Nikica {🧙} - avatar