Split number into sum components

后端 未结 9 2185
-上瘾入骨i
-上瘾入骨i 2021-02-12 18:07

Is there an efficient algorithm to split up a number into N subsections so that the sum of the numbers adds up to the original, with a base minimum? For example, if

9条回答
  •  南旧
    南旧 (楼主)
    2021-02-12 18:35

    Let me write it in Python.

    Let's say that you have 50 elements to split into 7 boxes and you want at least two inside each of them.

    N_init = 50
    s = 2
    m = 7
    

    We put s elements by default in each box so we are left with N elements.

    N = N_init - s*m
    

    We draw m random numbers, sort them, append N on the back. This is like inserting randomly m bookmarks in a book of N pages. The number of pages between consecutive bookmarks is random. (We had s so that we are sure that each box has at least s elements)

    a = sorted([random.randint(0,N+1) for i in range(m)])
    a.append(N)
    result = [j-i+s for(i,j) in zip(a[0:m],a[1:m+1])]
    

    Done!

提交回复
热议问题