tags:

views:

79

answers:

4

if have multiples object, how to arrange it so that each number of object in row x column will form a near square?

exp:14 objects arrange to something like this:

0 0 0 0
0 0 0 0
0 0 0 0
0 0
+6  A: 

Take the ceil of the square root?

in python:

import math
ceil(14**(.5))

Which returns:

>>> from math import ceil
>>> ceil(14**(.5))
4.0
Enrico Carlesso
+2  A: 

Get the square root of the number of items:

n = 14 ^ 0.5 ~ 3.7417

Round up to the nearest integer:

n = ceil(14 ^ 0.5) = 4

Now simply arrange the items in rows of n items until you run out.

Guffa
+1  A: 

Given n objects, the size of the resulting "square" is ceil(sqrt(n)), with special shortcut cases for n = 0 (don't draw anything) or n = 1 (just a 1x1 square).

Also, the question title is a little misleading. You can never arrange N objects in an NxN square, unless N is 1.

John Feminella
`ceil(sqrt(0)) == 0` and `ceil(sqrt(1)) == 1`; there should be no need for special cases.
Thomas
@Thomas: Mathematically, they're not special cases. Programmatically, they are; it's very common to have shortcut conditions that execute simpler versions of an algorithm when you only have to deal with zero or one things.
John Feminella
If special cases are handled just as well by the general case, why add extra code to write, read, debug and maintain? Unless this code is actually a performance bottleneck, and the shortcuts do speed things up; but adding them should be the exception, not the rule.
Thomas
+2  A: 

That depends. Assuming that the number of columns should be equal to or greater than the number of rows then the following calculates the number of columns (in pseudo-code):

Ceiling(Sqrt(n))

where n is the number of items.

Jakob Christensen