Question

By reviewing this and this, I've come up with a function, that's probably more complex than it should be, but, man, my math sux:

function tablize(elements)
{
    var root = Math.floor(Math.sqrt(elements));

    var factors = [];

    for (var i = 1; i <= root; i++)
    {
        if (elements % i === 0)
        {
            factors.push([i, elements / i]);
        }
    }

    var smallest = null;

    for (var f = 0; f < factors.length; f++)
    {
        var factor = factors[f];

        var current = Math.abs(factor[0] - factor[1]);

        if (!smallest || factors[smallest] > factor)
        {
            smallest = f;
        }
    }

    return factors[smallest];
}

While this does work, it provides results I'm not satisfied with.

For instance - 7, it's divided in 1x7, where I'd like it to be 3x3. That's the minimum, optimal, grid size needed to fill with 7 elements.

Also - 3, it's divided in 1x3, where I'd like it to be 2x2.

I need this for a live camera feed frame distribution on a monitor, but I'm totally lost. The only way I can think of is building an extra function to feed with previously generated number and divide again, but that seems wrong.

What is the optimal solution to solve this?

Était-ce utile?

La solution

For squares:

function squareNeeded(num) {
    return Math.ceil(Math.sqrt(num));
}

http://jsfiddle.net/aKNVq/

(I think you mean the smallest square of a whole number that is bigger than the given amount, because if you meant a rectangle, then your example for seven would be 2*4 instead of 3*3.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top