Determine rows/columns needed given a number

The "usual" way of handling this problem is by saying that there will always be N columns (less often, always N rows). The problem then becomes a matter of taking the number of items, dividing by N, and that's the number of rows you have (plus one if there's a remainder).

Changing the size of the grid makes for a confusing user interface. Users won't understand why the size of the grid keeps changing. They won't really wonder about it, but they'll be confused by the seemingly random changes.

If you still want to do what you're saying, I think you'll need to define your problem a little better. Is there a maximum number of items that can fit on the grid? Is there a maximum number of columns that you'll allow? For example, if you allow 50 items, should they be in 25 rows of 2 items? 5 rows of 10 items? 10 rows of 5 items?

At some point you'll have to either scroll horizontally or say, "maximum number of columns is X". And if you're going to impose that maximum number of columns, then you're better off just saying "There will always be X columns."

Unless there's a compelling reason to do the variable-dimension grid that you ask for, you're way better off just fixing the number of columns. It makes for trivially simple code rather than some complicated hack, and it presents a much more consistent interface to your users.


Idea: If square root is not integer, floor it, then divide whole number by this, ceil it.

int columns = (int)sqrt(number);
int lines = (int)ceil(number / (float)columns);

Example: 21 => columns = 4, lines = 6.

UPDATE: bonus, it also works when sqrt(number) is integer. No rounding occurs anywhere, and values are correct.