Search code examples
arraysalgorithmloopsdivide

limits of equal portions of a list with last portion getting all excess


I'm looking for the best way to divide a given list for example list with 200 numbers.
I'd like to divide it into 3 parts, so I know there is a remainder for example.
This is what I came with, I'm sure there is better way:

int divider = 3;
int lastElements = this.mylist.size() % divider;
int listpart = this.mylist.size() / divider;
int listpartStart = 0;
int listpartEnd = listpart-1;
for(int i=0;i<divider;i++) {
  if(i==divider-1) {
      listpartEnd+=lastElements;
  }
   
  listpartEnd;
  listpartStart;

   
  someHandlingFunction(listpartStart,listpartEnd);
     
  listpartEnd+=listpart;
  listpartStart+=listpart;
}

Solution

  • The key to coming up with a concise implementation of this requirement is to recognize that the final part, the one that should get the excess, is a special case. So, loop divisor-1 times and then handle the final part separately at the end.

    void split(int size, int divider)
    {
        int part = size / divider;
        for(int i=1; i<divider; i++)
        {
            someHandlingFunction((i-1)*part, (i*part)-1);
        }
        someHandlingFunction((divider-1)*part, size-1);
    }
    
    void someHandlingFunction(int start, int end) 
    {
        System.out.println(start + " - " + end);
    }
    

    Note - you may want to add a check for the case where size < divider and handle it appropriately.

    Test:

    split(200, 3);
    

    Output:

    0 - 65
    66 - 131
    132 - 199