2

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.

deewreck
  • 113
  • 7
  • errm `localities.collate( localities.size().intdiv(4) + 1 )`? – injecteer Jan 10 '23 at 11:39
  • thanks for input @injecteer.. since i mentioned in question, then size here of 163 isn't constant and may vary. but i need to have only 4 sublist at any time. adding +1 would adjust for current output of 3 reminder. – deewreck Jan 10 '23 at 11:53

1 Answers1

2

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
}
injecteer
  • 20,038
  • 4
  • 45
  • 89