Size algorithm

Well, here is a little problem I would like to help with.

I have a view, and the size of the viewport will depend on the user's screen resolution. The viewport should contain N fields that are aligned next to each other from right to left and occupy the entire horizontal space in the viewport. Now, if all the boxes can be the same size, it will be easy, just divide the width of the viewport by N and you will leave.

The problem is that each box should be 10% smaller than the box on the left side, for example, if the viewport has a width of 271 pixels, and three boxes will be returned [100, 90, 81]

So, I need an algorithm that, when transmitting the width of the viewport and the number of horizontal fields, will return an array containing the width of which each of the fields should be in order to fill the width of the viewport and reduce each box size by 10%.

Answers in any OO language are cool. I would like to get some ideas on how to approach this and maybe see who can come up with the most elegant solution.

Hello,

Chris

+3
source share
7 answers

Using simple geometric progression, in Python,

def box_sizes(width, num_boxes) :
    first_box = width / (10 * (1 - 0.9**n))
    return [first_box * 0.9**i for i in range(n)]

>>> box_sizes(100, 5)
[24.419428096993972, 21.977485287294574, 19.779736758565118, 17.801763082708607, 16.021586774437747]
>>> sum(_)
100.00000000000001

You might want to remove precision or convert to integers, but that should do it.

+4
source

This is really a math problem. With two fields:

x = n = P =

x + 0.9x = P

3: x + 0.9x + 0.81x = P
4: x + 0,9x + 0,81x + 0,729x = P

:

S (n) = a + ar + ar n +... + ar n-1

:

a =
r = 0,9
S (n) = P

S (n) = a (1-r n)/(1-r)

x = 0,1P/(1-0,9 n)

(!) (P, n).

+3

, . . , cletus f (n). .:)

+2
Let:
x = size of the first box
n = number of boxes
P = number of pixels

n = 1: x = P
n = 2: x + .9x = P
n = 3: x + .9x + .81x = P

P = x sum[1..n](.9 ^ (n - 1))

Therefore:
x = P / sum[1..n](.9 ^ (n - 1))

Using the Geometric Progression formula:
x = P (.9 - 1) / ((.9 ^ n) - 1))

Test:
P = 100
n = 3
Gives:
x = 36.9
+1
    public static int[] GetWidths(int width, int partsCount)
    {
        double q = 0.9;
        int[] result = new int[partsCount];

        double a = (width * (1 - q)) / (1 - Math.Pow(q, partsCount));

        result[0] = (int) Math.Round(a);
        int sum = result[0];

        for (int i = 1; i < partsCount - 1; i++)
        {
            result[i] = (int) Math.Round( a * Math.Pow(q, i) );
            sum += result[i];
        }

        result[partsCount - 1] = width - sum;

        return result;
    }

, .

+1

, , 1, 0,81 .. . ( )/( ).

0

, . W N, X. N ,

X + 0.9 X + 0.9 ^ 2 X +... + 0.9 ^ ( N - 1) X <= W

{1 + 0.9 + 0.9 ^ 2 +... + 0.9 ^ ( N -1)} X <= W

,

(1 - 0,9 ^ N) X/(1 - 0,9) <= W

X <= 0,1 W/(1 - 0,9 ^ N)

, , X.

0

Source: https://habr.com/ru/post/1702240/


All Articles