I have a 2D array of a given size and a list of numbered rectangles to fit into this space. Each of these rectangles has a known fixed height and width. The 2D array is guaranteed to be large enough to conveniently place all the rectangles.
I need to randomly put each of these rectangles in an array so as not to overlap and put everything. They can be placed in any orientation. Imagine that you place your ships in a battleship game, just with many different sizes of the ship and a much larger grid.
The finished array should look something like this: (0 represents empty space, a nonzero number represents the number of rectangles)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0 0 0 4 4 4 0
0 1 1 0 2 2 2 2 2 0 0 0 4 4 4 0
0 1 1 0 2 2 2 2 2 0 0 0 0 0 0 0
0 0 0 0 2 2 2 2 2 0 0 0 0 0 0 0
0 0 0 0 2 2 2 2 2 0 5 5 0 0 0 0
0 3 3 3 3 3 0 0 0 0 5 5 0 0 0 0
0 3 3 3 3 3 0 7 7 7 5 5 6 6 0 0
0 0 0 0 0 0 0 7 7 7 5 5 6 6 0 0
One approach that I examined relates to each rectangle, selects random placement and orientation, tries to fit it into the matrix. If a collision is detected with a previously placed block, try again. This would probably be the easiest to implement, but it doesnโt seem very efficient and doesnโt end in an explicitly deterministic way (the rectangle at the end of the list may collide with previously generated blocks for a long time).
Is there a better way to do this that would not be so problematic for placing later rectangles?
source share