This question already has an answer here:
- Split list into multiple lists with fixed number of elements 5 answers
I would like to subdivide a list into lists of list with a max size for each sublist. For example, given List(1,2,5,3,90,3,4,1,0,3)
and max size of sublists defined as 4, I would like to get List(List(1,2,5,3), List(90,3,4,1), List(0,3))
back.
This is what has already been done:
val l: List[Int] = ???
val subSize: Int = 4
val rest: Int = if(l.size % subSize == 0) 1 else 0
val subdivided: List[List[Int]] = for{
j <- List.range(0, l.size/subSize - rest, 1)
}yield{
for{
i <- List.range(subSize*j,subSize*j+3,1)
if(i < l.size)
}yield{
l(i)
}
}
Is there a better, more functional way of doing this?