Maths Help - Calculate for a Grid

I have a grid, 40x40 so there are 1600 points in it and I want to have 20 different areas all with random sizes that must fit inside the grid.

Think it of it as a continent as a square and I want to fit in 20 countries into it of different random areas sizes.

Anyone know how the maths works for this?

Entire books are written on this - the keyword to search for is rectangle packing.

Thanks, it might be a little beyond me but at least I’ve got an idea

Are you aiming at having 100% coverage. Do those 20 areas fully cover the 40x40 grid? No empty spaces left?

It doesn’t have to have full coverage, any points not covered can be allocated to a dead space

What I was thinking was to randomly get values for x and y for the 1st area size then randomly choose an x/y coordinate of where to fit this 1st area in. Then I’d have some loop probably repeating trying to fit it in the remaining areas by checking the grid for free spots and as the grid fills probably adjusting the area size to fit in a free space.

It’ll be quite inefficient but only needs to be done once. Was just wondering if there was a more elegant way

The elegant way is via the rectangle packing. The brute force you described would work. Ugly, indeed.