1D array to "most square" 2D array...

Ive been wondering about the following problem…

Given a 1D array of n values,

I want to find a 2D array to store it… But the array has to be as “square as possible”,

x_dimension - y_dimension = m
|m| has to be as small as possible.

and without any padding, ie: dummy values filling the array…

Any help?

does no seem so hard :

x = ceil(sqrt(n));
y = ceil(n*1.0/x);

Here is what i ended up using, if anyone has anything bit better, please let me know, as i find this solution a bit nasty…

//given array_size (size of the 1D array)
//work out 2D array dimensions.

float dimX = sqrt(array_size);

	if(array_size%dimX==0) helper=0;

dimY = array_size/dimX;

Thanks for the reply ZbuffeR,

However with your approach, the 2D array will mostimes be bigger then N. I dont want this…


Ah ok I reversed your priorities. Your strongest need is that there is “not padding at all”, I first though is was “as square as possible”.