Algorithm for subdividing an array into “semi-equal”, uniform sub-arrays

前端 未结 2 1852
独厮守ぢ
独厮守ぢ 2021-01-06 03:08

Given an array with N elements, I am looking for M (M < N) successive sub-arrays with equal lengths or with lengths that differ by mostly 1. For example, if N = 12 and M

相关标签:
2条回答
  • 2021-01-06 03:36

    If your language has integer division that truncates, an easy way to compute the size of section i is via (N*i+N)/M - (N*i)/M. For example, the python program

      N=100;M=12
      for i in range(M): print (N*i+N)/M - (N*i)/M
    

    outputs the numbers 8 8 9 8 8 9 8 8 9 8 8 9. With N=12;M=5 it outputs 2 2 3 2 3. With N=12;M=3 it outputs 4 4 4.

    If your section numbers are 1-based rather than 0-based, the expression is instead (N*i)/M - (N*i-N)/M.

    0 讨论(0)
  • 2021-01-06 03:38

    Space-filling-curves and fractals subdivide the plane and reduce the complexity. There is for example z-curve, hilbert curve, morton curve.

    0 讨论(0)
提交回复
热议问题