The balanced arrangement of n elements in the grid

I have a list of n logos to display in the grid with a maximum of 3 per line. What algorithm determines the number of displayed lines per line so that the number of logos per line is as balanced as possible, without using more than the minimum possible number of lines?

For instance:

 n -> number in each row
 1 -> 1
 2 -> 2
 3 -> 3
 4 -> 2, 2
 5 -> 3, 2
 6 -> 3, 3
 7 -> 3, 2, 2
 8 -> 3, 3, 2
 9 -> 3, 3, 3
10 -> 3, 3, 2, 2
+3
source share
4 answers
  • For N <= 3, just use N.
  • If N is exactly divisible by 3, then use: 3 3 ... 3
  • If N divided by 3 has a remainder of 1, then use: 3 3 ... 2 2
  • If N divided by 3 has a remainder of 2, then use: 3 3 ... 3 2
+11
source

How confusing your question is, I think you need to first determine:

number_of_rows = ceil(number_of_logos / 3.0)

.

Python:

import math
def partition_logos(count, lsize):
    num_lines = int(math.ceil(count / float(lsize)))
    partition = [0] * num_lines
    for i in xrange(count):
        partition[i%num_lines] += 1
    return partition

>>> for i in xrange(1,11):
...     print partition_logos(i, 3)
[1]
[2]
[3]
[2, 2]
[3, 2]
[3, 3]
[3, 2, 2]
[3, 3, 2]
[3, 3, 3]
[3, 3, 2, 2]
+6

n/3 n% 3

edit: ok, I saw that you edited your question .... I didn’t see that you want to display 2 in each line if it is 4 logos. but then you can use n mod 3 to calculate if this is a reminder, as others have suggested

if n% 3 = 0, then just put 3 logos in each line if n% 3 = 1, then put the last 4 logos in two lines if n% 3 = 2, then put 3 logos in n line and the last 2 logos in a separate line

+1
source

Recursive solution in Python:

def logos_by_row(N, rows):
    width = 0
    if N > 4 or N == 3:
        width = 3
    elif N == 4 or N == 2:
        width = 2
    elif N == 1:
        width = 1

    if width != 0:
        rows.append(width)
        logos_by_row(N - width, rows)


answer = []
for i in range(10):
    logos_by_row(i+1, answer)
print answer
+1
source

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


All Articles