listgroovycollate

divide list to sublists in groovy


I am trying to divide a list of string into 4 sublist (which should have all elements of original list balanced among them). I have tried following approach but i am getting reminder elements into a 5th list. I need only four sublists and reminder must be adjusted into these four list only

def sublists = localities.collate(localities.size().intdiv(4))

 for(sublist in sublists){
    println(sublist.join(','))
    println "next"
}

here localities is having around 163 elements, I am getting output as 4 list of 40 and 5th list of size 3.. my localities list is dynamic and could have variable number (will always be above 100) . i need to get only 4 list, where reminder of 3 elements are adjusted in 4 list.


Solution

  • Something like this:

    def split( list ){
      int size = Math.ceil( list.size() / 4 )
      list.collate size
    }
    
    assert split( 1..163 )*.size() == [41, 41, 41, 40]
    assert split( 1..157 )*.size() == [40, 40, 40, 37]
    assert split( 1..100 )*.size() == [25, 25, 25, 25]
    assert split( 1..4 )*.size()   == [1, 1, 1, 1]
    
    //edge cases
    assert split( 1..3 )*.size() == [1, 1, 1]
    assert split( 1..2 )*.size() == [1, 1]
    
    // for all lengths above 4 exactly 4 groups are returned
    4..200.each{
      assert split( 1..it ).size() == 4
    }