Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

neatly pack items into a rectangular box

I can't think of a more elegant way to explain this. So I have a rectangular container and a variable number of items and I want to fill the container evenly like so

if the aspect ratio of the container is 1.5 and I have 6 items, columns should probably be 3

x x x
x x x

if the aspect ratio of the container is 2.0 and I have 32 items, columns should probably be 8

x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x x x

if by chance the ratio is 2.0 and I have 30 items, columns should probably still be 8

x x x x x x x x
x x x x x x x x
x x x x x x x x
x x x x x x

and so on. I feel like this should be simple but I can't think of a simple way to do it. the input would be items, width, and height, and the output would be columns (rows would fill out themselves)

thanks


1 Answers

The formula I got is sqrt(items/aspect_ratio) * aspect_ratio. You can round this result up to get the desired result in scenario 3.

How I got it:

'aspect ratio just seems to be scale of the number of rows; as such 
columns = rows * aspect ratio
also 
items = rows * columns 
now subbing in / algebra
rows^2 * aspect ratio = items
rows = sqrt(items/aspect ration)
columns = sqrt(items/ aspect ratio) * aspect ratio'
like image 80
Mitch Avatar answered Jun 27 '26 13:06

Mitch