views:

92

answers:

2

Ok here's what I'm trying to accomplish. Say I have 100 items. I want to create a "grid"(each Item consisting of an x, y point). I want the grid to be as close to a square as possible. Is there any kind of math to determine the grid width, and grid height i'd need by just a single number?(By grid width and height I mean the number of x items, and the number of Y items)

Now that I think about it would it be efficient to take the square root of the number, say varI=sqrt(45), remove the decimal place from varI...X=varI...then Y would be varI+1?

+1  A: 

There are several issues to consider here. If you want your grid to be as square as possible, for many Ns it will have empty cells in it. A simple example is N=10. You can create a 3x4 grid for it, but it will have two empty cells. A 2x5 grid, on the other hand, will have no empty cells. Some Ns (prime numbers) will always have empty cells in the grid.

But if you just want the square and don't care about empty fields then generally yes, you should take the square root. Say your number is N. Then, take R = int(sqrt(N)). Next, do an integer division N/R, take the quotient and add 1 to it. This is C. The grid is RxC. Note that when N is a square (like 100), this is a special case so don't add 1 to the quotient.

Example:

N = 40
R = int(sqrt(N)) = 6
C = int(40 / 6) + 1 = 7
grid is 6x7
Eli Bendersky
+2  A: 

The square root is precisely what you need.

N
x=floor(sqrt(N))
y=raise(N/x)

This is the minimum rectangle that has more than N places and is closest to a square.

Now... if you want to find a rectangle that has exactly N places and is closest to a square...that's a different problem.

You need to find a factor of N, x, that's closest

You have to run through the factors of N and find the closest to sqrt(N). Then the rectangle is x by N/x, both integers.

Ezequiel